48 lines
1.1 KiB
JavaScript
48 lines
1.1 KiB
JavaScript
|
'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({ id: item.id })
|
||
|
.update(item)
|
||
|
.into(table)))),
|
||
|
]);
|
||
|
}
|
||
|
|
||
|
return { insert, update };
|
||
|
}
|
||
|
|
||
|
module.exports = upsert;
|