Skip to content

Commit 1a4067d

Browse files
committed
Adds beforeDefine to plugins (#263)
Prototype: beforeDefine(name, properties, options)
1 parent 394944f commit 1a4067d

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

lib/ORM.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,12 @@ ORM.prototype.define = function (name, properties, opts) {
199199
properties = properties || {};
200200
opts = opts || {};
201201

202+
for (var i = 0; i < this.plugins.length; i++) {
203+
if (typeof this.plugins[i].beforeDefine == "function") {
204+
this.plugins[i].beforeDefine(name, properties, opts);
205+
}
206+
}
207+
202208
this.models[name] = new Model({
203209
db : this,
204210
settings : this.settings,

test/integration/db.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,28 @@ describe("db.use()", function () {
3535
return done();
3636
});
3737

38+
it("a plugin should be able to catch models before defining them", function (done) {
39+
var MyPlugin = require("../support/my_plugin");
40+
var opts = {
41+
option : true,
42+
calledDefine : false,
43+
beforeDefine : function (name, props, opts) {
44+
props.otherprop = Number;
45+
}
46+
};
47+
48+
db.use(MyPlugin, opts);
49+
50+
var MyModel = db.define("my_model", { // db.define should call plugin.define method
51+
property: String
52+
});
53+
54+
opts.calledDefine.should.be.true;
55+
MyModel.properties.should.have.property("otherprop");
56+
57+
return done();
58+
});
59+
3860
it("should be able to register a plugin as string", function (done) {
3961
var opts = {
4062
option : true,

test/support/my_plugin.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module.exports = function MyPlugin(DB, opts) {
2-
opts.should.eql({ option: true, calledDefine: false });
2+
opts.option.should.be.true;
3+
opts.calledDefine.should.be.false;
34

45
return {
56
define: function (Model) {
@@ -8,6 +9,11 @@ module.exports = function MyPlugin(DB, opts) {
89
Model.id[0].should.be.a("string");
910

1011
opts.calledDefine = true;
12+
},
13+
beforeDefine: function (model_name, model_props, model_opts) {
14+
if (opts.beforeDefine) {
15+
opts.beforeDefine(model_name, model_props, model_opts);
16+
}
1117
}
1218
};
1319
};

0 commit comments

Comments
 (0)