Created
October 18, 2016 14:22
-
-
Save armand1m/b2bd6b551d3c1f2b7254bcb339c0d869 to your computer and use it in GitHub Desktop.
A bulkUpsert function using Promises and the Sequelize API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function bulkUpsert(model, key, values) { | |
function _find(where) { | |
return model.findOne({ where }) | |
} | |
function _update(value, where) { | |
return model | |
.update(value, { where }) | |
.then(() => _find(where)) | |
} | |
let promises = | |
values.map(value => { | |
let where = { | |
[key]: value[key] | |
} | |
return model | |
.findOrCreate({ where, defaults: value }) | |
.spread((result, created) => { | |
return (!created) | |
? _update(value, where) | |
: Promise.resolve(result) | |
}) | |
}) | |
return Promise.all(promises) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment