From 1a4067d5686c65d5b599a90820feef6e71bca624 Mon Sep 17 00:00:00 2001 From: Diogo Resende Date: Thu, 1 Aug 2013 17:43:49 +0100 Subject: [PATCH] Adds beforeDefine to plugins (#263) Prototype: beforeDefine(name, properties, options) --- lib/ORM.js | 6 ++++++ test/integration/db.js | 22 ++++++++++++++++++++++ test/support/my_plugin.js | 8 +++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/lib/ORM.js b/lib/ORM.js index b3ebbd93..85e25bd3 100644 --- a/lib/ORM.js +++ b/lib/ORM.js @@ -199,6 +199,12 @@ ORM.prototype.define = function (name, properties, opts) { properties = properties || {}; opts = opts || {}; + for (var i = 0; i < this.plugins.length; i++) { + if (typeof this.plugins[i].beforeDefine == "function") { + this.plugins[i].beforeDefine(name, properties, opts); + } + } + this.models[name] = new Model({ db : this, settings : this.settings, diff --git a/test/integration/db.js b/test/integration/db.js index 39d7f2ee..96dffede 100644 --- a/test/integration/db.js +++ b/test/integration/db.js @@ -35,6 +35,28 @@ describe("db.use()", function () { return done(); }); + it("a plugin should be able to catch models before defining them", function (done) { + var MyPlugin = require("../support/my_plugin"); + var opts = { + option : true, + calledDefine : false, + beforeDefine : function (name, props, opts) { + props.otherprop = Number; + } + }; + + db.use(MyPlugin, opts); + + var MyModel = db.define("my_model", { // db.define should call plugin.define method + property: String + }); + + opts.calledDefine.should.be.true; + MyModel.properties.should.have.property("otherprop"); + + return done(); + }); + it("should be able to register a plugin as string", function (done) { var opts = { option : true, diff --git a/test/support/my_plugin.js b/test/support/my_plugin.js index b8e68eba..d75f6951 100644 --- a/test/support/my_plugin.js +++ b/test/support/my_plugin.js @@ -1,5 +1,6 @@ module.exports = function MyPlugin(DB, opts) { - opts.should.eql({ option: true, calledDefine: false }); + opts.option.should.be.true; + opts.calledDefine.should.be.false; return { define: function (Model) { @@ -8,6 +9,11 @@ module.exports = function MyPlugin(DB, opts) { Model.id[0].should.be.a("string"); opts.calledDefine = true; + }, + beforeDefine: function (model_name, model_props, model_opts) { + if (opts.beforeDefine) { + opts.beforeDefine(model_name, model_props, model_opts); + } } }; };