Skip to content

Commit

Permalink
fix: record comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
carlbrugger committed Oct 30, 2023
1 parent 7ca9341 commit 32d96dc
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-parents-worry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@flatfile/plugin-record-hook': patch
---

Fix to compare full Record objects instead of just Record values
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 29 additions & 6 deletions plugins/record-hook/src/RecordHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,18 @@ export const BulkRecordHook = async (
return
}

await event.cache.init<FlatfileRecords<any>>('originalRecords', fetchData)

// Execute client-defined data hooks
await asyncBatch(batch.records, handler, options, event)

event.afterAll(async () => {
const batch = event.cache.get<FlatfileRecords<any>>('records')
const modifiedRecords = batch.records.filter(hasRecordChanges)
const originalRecords =
event.cache.get<FlatfileRecords<any>>('originalRecords')
const modifiedRecords = batch.records.filter((record) =>
hasRecordChanges(record, originalRecords.records)
)
if (!modifiedRecords || modifiedRecords.length === 0) {
if (options.debug) {
console.log('No records modified')
Expand All @@ -105,12 +111,29 @@ export const BulkRecordHook = async (
return handler
}

const hasRecordChanges = (record: FlatfileRecord) => {
const messageCount = record.toJSON().info.length
return (
JSON.stringify(record.originalValue) !== JSON.stringify(record.value) ||
messageCount > 0
const hasRecordChanges = (
record: FlatfileRecord,
originalRecords: FlatfileRecord[]
) => {
const originalRecord = originalRecords.find(
(original) => original.rowId === record.rowId
)
return !deepEqual(originalRecord, record)
}

function deepEqual(obj1, obj2) {
if (obj1 === obj2) return true

const keysA = Object.keys(obj1)
const keysB = Object.keys(obj2)

if (keysA.length !== keysB.length) return false

for (let key of keysA) {
if (!keysB.includes(key) || !deepEqual(obj1[key], obj2[key])) return false
}

return true
}

const prepareXRecords = async (records: any): Promise<FlatfileRecords<any>> => {
Expand Down

0 comments on commit 32d96dc

Please sign in to comment.