Skip to content

Instantly share code, notes, and snippets.

@ricardograca
Last active December 9, 2018 00:37
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 ricardograca/da68dc091fcbe15c395558c166fd7200 to your computer and use it in GitHub Desktop.
Save ricardograca/da68dc091fcbe15c395558c166fd7200 to your computer and use it in GitHub Desktop.
Bookshelf previousAttributes() on updated event
var assert = require('assert')
var knex = require('knex')({
client: 'sqlite3',
connection: {filename: ':memory:'}
})
var bookshelf = require('bookshelf')(knex)
var User = bookshelf.Model.extend({
tableName: 'users',
initialize: function() {
this.on('updated', function(user) {
console.log(user.previousAttributes())
})
}
})
return knex.schema.createTable('users', function(table) {
table.increments()
table.text('status').notNullable()
}).then(function() {
return knex('users').insert({status: 'active'})
}).then(function () {
return new User({id: 1}).fetch()
}).then(function(user) {
assert.strictEqual(user.get('status'), 'active')
user.set('status', 'active')
return user.save()
}).then(function() {
console.log('all done')
}).catch(function (err) {
console.log(err)
console.log(err.stack)
}).finally(function() {
process.exit()
})
{
"name": "bookshelf_previousattributes",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Ricardo Graça <ricardo@devius.net>",
"license": "ISC",
"dependencies": {
"bookshelf": "git+https://github.com/bookshelf/bookshelf.git",
"knex": "^0.15.2",
"sqlite3": "^4.0.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment