Skip to content

Instantly share code, notes, and snippets.

@jeffsoup
Last active July 31, 2021 02:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffsoup/8b7d023744b93bae0decdc664ddfacb2 to your computer and use it in GitHub Desktop.
Save jeffsoup/8b7d023744b93bae0decdc664ddfacb2 to your computer and use it in GitHub Desktop.
Small Example of A Bookshelf Transaction
import config from '../src/config'
import chai, { expect, should, assert } from 'chai'
import _ from 'lodash'
const knex = require('knex')(config.database)
const bookshelf = require('bookshelf')(knex)
const Test = bookshelf.Model.extend({
tableName: 'TEST_ONLY',
idAttribute: 'ID',
softDelete: false
})
// //Standard Chai Style
it('Testing Creating Notification Setting Record', function() {
//Just to get a random value
const value = Math.floor((Math.random() * 10000) + 1).toString()
let obj = {
NAME: value
}
return createNsWithTransaction(obj).then(function(data) {
let res = data.toJSON()
expect(value).to.equal(res.NAME)
})
})
function createNsWithTransaction(object) {
//With Promises
return new Promise(async (resolve, reject) => {
bookshelf.transaction(async (t) => {
try {
const model = await Test.forge(object).save(null, { transacting: t })
//This commits the Transaction
resolve(model)
} catch (err) {
logger.error(' Test Failed', err)
await this.rollbackTransaction(t)
reject(err)
}
})
})
}
@danieltichiyama
Copy link

Thank you for this!

@jeffsoup
Copy link
Author

Awesome, glad it was helpful.

@yusufali2205
Copy link

This was helpful, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment