Skip to content

Commit

Permalink
[Issue mozilla-sensorweb#228] consumers to add model hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Russ Nicoletti committed Jan 24, 2017
1 parent adf2fd8 commit 091d392
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
11 changes: 10 additions & 1 deletion example/example.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@ const config = {
port: 5432,
name: 'sensorthingsexample',
user: 'postgres',
password: '12345678'
password: '12345678',
hooks: {
'beforeCreate': (instance, options) => {
if (instance.$modelOptions.name.plural === 'Things') {
instance.properties = Object.assign({}, instance.properties, {
MozillaSensorWebOwner: 'client-name'
});
}
}
}
}
};

Expand Down
23 changes: 23 additions & 0 deletions src/models/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ const IDLE = 0
const INITIALIZING = 1;
const READY = 2;

const hooks = [
'beforeValidate',
'afterValidate',
'beforeCreate',
'afterCreate',
'beforeDestroy',
'afterDestroy',
'beforeRestore',
'afterRestore',
'beforeUpdate',
'afterUpdate'
];

const Deferred = function Deferred () {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
Expand All @@ -43,6 +56,7 @@ let state = IDLE;
let db = null;

export default config => {

if (state === READY) {
return Promise.resolve(db);
}
Expand Down Expand Up @@ -82,6 +96,15 @@ export default config => {
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}

if (!config.hooks) {
return;
}

hooks.forEach(hook => {
const clientHook = config.hooks[hook];
clientHook && db[modelName].hook(hook, clientHook);
});
});

db.sequelize = sequelize;
Expand Down

0 comments on commit 091d392

Please sign in to comment.