* Calculates the bulk write operations (upserts/deletes) based on the diff * between old and new record arrays. * @param oldData Array of records from the old file version. * @param currentData Array of records from the current file version. * @param filepath Current path of the file (for loggin
( oldData: any[], currentData: any[], filepath: string )
| 69 | * @returns An object containing the operations array and skipped record count. |
| 70 | */ |
| 71 | function calculateBulkOperations( |
| 72 | oldData: any[], |
| 73 | currentData: any[], |
| 74 | filepath: string |
| 75 | ): { operations: AnyBulkWriteOperation<Document>[]; skippedRecords: number } { |
| 76 | const operations: AnyBulkWriteOperation<Document>[] = []; |
| 77 | let skippedRecords = 0; |
| 78 | |
| 79 | const oldRecordsMap = new Map(oldData.map((r) => [r.index, r])); |
| 80 | const newRecordsMap = new Map(currentData.map((r) => [r.index, r])); |
| 81 | |
| 82 | // Find Added/Modified records |
| 83 | for (const [index, newRecord] of newRecordsMap.entries()) { |
| 84 | if (index === undefined || index === null || index === '') { |
| 85 | console.warn(`Record in ${filepath} is missing a valid 'index' field...`); |
| 86 | skippedRecords++; |
| 87 | continue; |
| 88 | } |
| 89 | const oldRecord = oldRecordsMap.get(index); |
| 90 | if (!oldRecord || diff(oldRecord, newRecord)) { |
| 91 | operations.push({ |
| 92 | [MONGO_OP_UPDATE_ONE]: { |
| 93 | filter: { index: index }, |
| 94 | update: { $set: { ...newRecord, [FIELD_UPDATED_AT]: new Date().toISOString() } }, |
| 95 | upsert: true, |
| 96 | }, |
| 97 | }); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // Find Deletions |
| 102 | for (const [index] of oldRecordsMap.entries()) { |
| 103 | // No need for oldRecord value here |
| 104 | if (index === undefined || index === null || index === '') continue; |
| 105 | if (!newRecordsMap.has(index)) { |
| 106 | console.log(` - Detected deletion for index: ${index}`); |
| 107 | operations.push({ [MONGO_OP_DELETE_ONE]: { filter: { index: index } } }); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | return { operations, skippedRecords }; |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Executes the MongoDB bulk write operation. |
no outgoing calls
no test coverage detected