All files / src/utils dataChanges.js

18.75% Statements 6/32
20% Branches 3/15
22.22% Functions 4/18
23.07% Lines 6/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58      13x       24x 24x 24x                                                                                   24x       24x    
import { nextIdApi } from '@/services/api'
 
export function cloneData(value) {
  return JSON.parse(JSON.stringify(value))
}
 
export function diffRows(current, previous) {
  const previousById = new Map(previous.map((item) => [String(item.b_id), item]))
  const currentById = new Map(current.map((item) => [String(item.b_id), item]))
  return {
    inserts: current.filter((item) => !previousById.has(String(item.b_id))),
    updates: current.filter((item) => {
      const old = previousById.get(String(item.b_id))
      return old && JSON.stringify(item) !== JSON.stringify(old)
    }),
    deletes: previous
      .filter((item) => !currentById.has(String(item.b_id)))
      .map((item) => ({ b_id: item.b_id })),
  }
}
 
export async function allocateTemporaryIds(rowGroups) {
  const temporaryIds = [
    ...new Set(
      rowGroups
        .flat()
        .map((row) => String(row?.b_id ?? ''))
        .filter((id) => /^-\d+$/.test(id)),
    ),
  ]
  if (!temporaryIds.length) return new Map()
  const res = await nextIdApi(temporaryIds.length)
  const ids = Array.isArray(res.data) ? res.data : [res.data]
  const mapping = new Map(temporaryIds.map((id, index) => [id, String(ids[index])]))
  rowGroups.flat().forEach((row) => {
    const id = mapping.get(String(row?.b_id))
    if (id) row.b_id = id
  })
  return mapping
}
 
export function remapForeignKeys(rows, fields, mapping) {
  rows.forEach((row) => {
    fields.forEach((field) => {
      const value = mapping.get(String(row[field]))
      if (value) row[field] = value
    })
  })
}
 
export function tableChange(table, changes) {
  return { table, key_field: 'b_id', ...changes }
}
 
export function hasChanges(request) {
  return request.inserts?.length || request.updates?.length || request.deletes?.length
}