diff --git a/lib/Model.js b/lib/Model.js index 188ba3a9..768798c0 100644 --- a/lib/Model.js +++ b/lib/Model.js @@ -16,7 +16,8 @@ var AvailableHooks = [ "beforeValidation", "beforeRemove", "afterRemove", "afterLoad", - "afterAutoFetch" + "afterAutoFetch", + "beforeQuery" ]; exports.Model = Model; @@ -368,7 +369,7 @@ function Model(opts) { conditions = Utilities.checkConditions(conditions, one_associations); } - var chain = new ChainFind(model, { + var query_params = { only : options.only || model_fields, id : opts.id, table : opts.table, @@ -400,7 +401,10 @@ function Model(opts) { }, cb); }, cb); } - }); + } + Hook.trigger(query_params, opts.hooks.beforeQuery, true); + + var chain = new ChainFind(model, query_params); if (typeof cb !== "function") { return chain; @@ -491,13 +495,16 @@ function Model(opts) { conditions = Utilities.checkConditions(conditions, one_associations); } - return new require("./AggregateFunctions")({ + var query_params = { table : opts.table, driver_name : opts.driver_name, driver : opts.driver, conditions : conditions, properties : properties - }); + } + Hook.trigger(query_params, opts.hooks.beforeQuery, true); + + return new require("./AggregateFunctions")(query_params); }; model.exists = function () { diff --git a/test/integration/hook.js b/test/integration/hook.js index a1e1bc68..b92ebdca 100644 --- a/test/integration/hook.js +++ b/test/integration/hook.js @@ -35,7 +35,8 @@ describe("Hook", function() { beforeSave : checkHook("beforeSave"), beforeValidation : checkHook("beforeValidation"), beforeRemove : checkHook("beforeRemove"), - afterRemove : checkHook("afterRemove") + afterRemove : checkHook("afterRemove"), + beforeQuery : checkHook("beforeQuery") }; } @@ -46,7 +47,10 @@ describe("Hook", function() { hooks : hooks }); - Person.settings.set("instance.returnAllErrors", false); + Person.settings.set("instance.returnAllErrors", false); + Person.count({}, function(e, c){ + //console.log(c) + }) return helper.dropSync(Person, done); }; @@ -106,6 +110,7 @@ describe("Hook", function() { }); }); + describe("beforeCreate", function () { before(setup()); @@ -212,7 +217,37 @@ describe("Hook", function() { }); }); }); - + describe('beforeQuery', function(){ + before(setup()); + + it("should trigger before query", function(done){ + + Person.beforeQuery(function(next){ + this.limit = 1; + }) + Person.create([{ name: "Jane Doe" }, { name: "Mary" }], function (err, items) { + + should.equal(items.length, 2); + Person.find({}, function(err, people){ + should.equal(people.length, 1); + return done(); + }) + }); + }) + + it("should trigger before query", function(done){ + + Person.beforeQuery(function(next){ + this.table = 'cat'; + }) + + Person.find({ name : "", id: 2}, function(err, people){ + should.exist(err); + //should.equal(people.length, 1); + return done(); + }) + }) + }) describe("afterCreate", function () { before(setup());