forked from DebaucheryLibrarian/traxxx
Refactored seed files to use programmatic upsert instead of SQL duplicate ignore.
This commit is contained in:
47
src/utils/upsert.js
Normal file
47
src/utils/upsert.js
Normal 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;
|
||||
Reference in New Issue
Block a user