Skip to content

Instantly share code, notes, and snippets.

@hinex
Created December 12, 2018 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hinex/017c7c98c4a163d766fe2191a65fd944 to your computer and use it in GitHub Desktop.
Save hinex/017c7c98c4a163d766fe2191a65fd944 to your computer and use it in GitHub Desktop.
Knex.js Insert or Update
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