traxxx/src/utils/upsert.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

'use strict';
async function upsert(table, items, duplicatesById, identifier = 'id', knex) {
const { insert, update } = items.reduce((acc, item) => {
if (duplicatesById[item[identifier]]) {
return {
...acc,
update: [
...acc.update,
{
...duplicatesById[item[identifier]],
...item,
},
],
};
}
return {
...acc,
insert: [
...acc.insert,
item,
],
};
},
{
insert: [],
update: [],
});
if (knex) {
console.log(`${table}: Inserting ${insert.length}`);
console.log(`${table}: Updating ${update.length}`);
return Promise.all([
knex(table).insert(insert),
knex.transaction(async trx => Promise.all(update.map(item => trx
.where({ [identifier]: item[identifier] })
.update(item)
.into(table)))),
]);
}
return { insert, update };
}
module.exports = upsert;