2019-11-06 01:47:10 +00:00
|
|
|
'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
|
2019-11-27 03:58:38 +00:00
|
|
|
.where({ [identifier]: item[identifier] })
|
2019-11-06 01:47:10 +00:00
|
|
|
.update(item)
|
|
|
|
.into(table)))),
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return { insert, update };
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = upsert;
|