Refactored seed files to use programmatic upsert instead of SQL duplicate ignore.

This commit is contained in:
2019-11-06 02:47:10 +01:00
parent e0542c26d7
commit 0567b1b2ff
6 changed files with 3883 additions and 3757 deletions

47
src/utils/upsert.js Normal file
View File

@@ -0,0 +1,47 @@
'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;