From 50ac48c5f7e0700ca6a80f6f56b248db7f84d329 Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Fri, 22 May 2015 09:03:27 -0700 Subject: [PATCH] Add hooks to sql based connectors --- lib/sql.js | 16 +++++++++++++++- test/sql.test.js | 22 +++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/lib/sql.js b/lib/sql.js index a89c069..91a8b29 100644 --- a/lib/sql.js +++ b/lib/sql.js @@ -397,7 +397,21 @@ SQLConnector.prototype.execute = function(sql, params, options, callback) { self.execute(sql, params, options, callback); }); } - this.executeSQL(sql, params, options, callback); + var context = { + req: { + sql: sql, + params: params + }, + options: options + }; + this.notifyObserversAround('execute', context, function(context, done) { + self.executeSQL(sql, params, options, function(err, info, extra) { + if (!err && info != null) { + context.res = info; + } + done(err, info, extra); + }); + }, callback); }; /** diff --git a/test/sql.test.js b/test/sql.test.js index 1a00d52..0488134 100644 --- a/test/sql.test.js +++ b/test/sql.test.js @@ -9,13 +9,14 @@ var ds = new juggler.DataSource({ debug: true }); var connector; +var Customer; describe('sql connector', function() { before(function() { connector = ds.connector; connector._tables = {}; connector._models = {}; - ds.createModel('customer', + Customer = ds.createModel('customer', { name: { id: true, @@ -307,4 +308,23 @@ describe('sql connector', function() { connector.execute('SELECT * FROM `CUSTOMER`', [], {}, 'xyz'); }).to.throw('callback must be a function'); }); + + it('should invoke hooks', function(done) { + var events = []; + connector.observe('before execute', function(ctx, next) { + expect(ctx.req.sql).be.a('string'); + expect(ctx.req.params).be.a('array'); + events.push('before execute'); + next(); + }); + connector.observe('after execute', function(ctx, next) { + expect(ctx.res).be.an('array'); + events.push('after execute'); + next(); + }); + Customer.find(function(err, results) { + expect(events).to.eql(['before execute', 'after execute']); + done(err, results); + }); + }); });