Last active
July 31, 2021 02:32
-
-
Save jeffsoup/8b7d023744b93bae0decdc664ddfacb2 to your computer and use it in GitHub Desktop.
Small Example of A Bookshelf Transaction
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
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) | |
} | |
}) | |
}) | |
} |
Awesome, glad it was helpful.
This was helpful, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this!