Created
December 12, 2018 16:03
-
-
Save hinex/017c7c98c4a163d766fe2191a65fd944 to your computer and use it in GitHub Desktop.
Knex.js Insert or Update
This file contains 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
const DB = require('../db') | |
const insertOrUpdate = (tableName, rows) => { | |
return DB.transaction((trx) => { | |
const queries = rows.map((tuple) => { | |
const insert = trx(tableName).insert(tuple).toString() | |
const update = trx(tableName).update(tuple).toString().replace(/^update(.*?)set\s/gi, '') | |
return trx.raw(`${insert} ON DUPLICATE KEY UPDATE ${update}`).transacting(trx) | |
}) | |
return Promise.all(queries).then(trx.commit).catch(trx.rollback) | |
}) | |
} | |
module.exports = { | |
insertOrUpdate, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment