traxxx/src/utils/upsert.js

43 lines
1.3 KiB
JavaScript
Raw Normal View History

'use strict';
async function upsert(table, items, identifier = 'id', knex) {
const duplicates = await knex(table).whereIn(identifier, items.map(item => item[identifier]));
const duplicatesByIdentifier = duplicates.reduce((acc, item) => ({ ...acc, [item[identifier]]: item }), {});
const { insert, update } = items.reduce((acc, item) => {
if (duplicatesByIdentifier[item[identifier]]) {
acc.update.push(item);
return acc;
}
acc.insert.push(item);
return acc;
}, {
insert: [],
update: [],
});
if (knex) {
console.log(`${table}: Inserting ${insert.length}`);
console.log(`${table}: Updating ${update.length}`);
const [inserted, updated] = await Promise.all([
knex(table).returning('*').insert(insert),
knex.transaction(async trx => Promise.all(update.map(item => trx
.where({ [identifier]: item[identifier] })
.update(item)
.into(table)
.returning('*')))),
]);
return {
inserted: Array.isArray(inserted) ? inserted : [],
updated: updated.reduce((acc, updatedItems) => acc.concat(updatedItems), []),
};
}
return { insert, update };
}
module.exports = upsert;