Skip to content

Instantly share code, notes, and snippets.

@jclem
Last active February 28, 2016 16:06
Show Gist options
  • Save jclem/17b895d4f58146d6ec4c to your computer and use it in GitHub Desktop.
Save jclem/17b895d4f58146d6ec4c to your computer and use it in GitHub Desktop.
Base Bookshelf Model
'use strict';
const _ = require('lodash');
module.exports = bookshelf => {
return bookshelf.Model.extend({
hasTimestamps: true,
initialize() {
this.on('saving', this.beforeSave);
this.on('saved', this.afterSave);
this.on('creating', this.beforeCreate);
this.on('created', this.afterCreate);
this.on('updating', this.beforeUpdate);
this.on('updated', this.afterUpdate);
},
format() {
const format = {};
if (this.isSaving && this.formatSave) {
_.merge(format, this.formatSave.apply(this, arguments));
}
if (this.isCreating && this.formatCreate) {
_.merge(format, this.formatCreate.apply(this, arguments));
}
if (this.isUpdating && this.formatUpdate) {
_.merge(format, this.formatUpdate.apply(this, arguments));
}
return format;
},
beforeSave() {
this.isSaving = true;
},
afterSave() {
this.isSaving = false;
},
beforeCreate() {
this.isCreating = true;
},
afterCreate() {
this.isCreating = false;
},
beforeUpdate() {
this.isUpdating = true;
},
afterUpdate() {
this.isUpdating = false;
},
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment