Created
November 11, 2017 07:05
-
-
Save israeleriston/3116284518ba8adc094116d839582c5b to your computer and use it in GitHub Desktop.
Wrap for query using Knex
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 knex = require('../../config/db') | |
const baseUsers = knex('users') | |
const tryCatch = fn => { | |
try { | |
return Promise.resolve(fn()) | |
} catch (e) { | |
return Promise.reject(e) | |
} | |
} | |
const sendCommit = (txt) => { | |
return txt.commit | |
} | |
const sendRollback = (txt) => { | |
return txt.rollback | |
} | |
const tryCommit = (txt, callback) => { | |
return tryCatch(callback) | |
.then(sendCommit) | |
.catch(sendRollback) | |
} | |
const insert = (txt, user) => { | |
return baseUsers | |
.transacting(txt) | |
.insert(user) | |
} | |
const handler = (callback, untilGetResult) => { | |
console.log(' handler ' + callback, untilGetResult) | |
return knex.transaction(txt => tryCommit(txt, callback(txt, untilGetResult))) | |
} | |
const beginTransaction = (callback, untilGetResult) => { | |
console.log(' beginTransaction callback ' + JSON.stringify(callback)) | |
console.log(' beginTransaction untilGetResult ' + JSON.stringify(untilGetResult)) | |
return tryCatch(handler) | |
} | |
const insertUser = (user) => { | |
console.log(' insertuser ' + JSON.stringify(user)) | |
return beginTransaction(insert, user) | |
} | |
module.exports = insertUser |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment