From dcf88baf681e748a6e88fbb4853b4219c83c1fbd Mon Sep 17 00:00:00 2001 From: juehou Date: Tue, 26 Apr 2016 00:35:54 -0400 Subject: [PATCH] Resolver support return promise --- common/models/role.js | 14 +++++++++++--- test/role.test.js | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/common/models/role.js b/common/models/role.js index 87bdee06..87a7d24c 100644 --- a/common/models/role.js +++ b/common/models/role.js @@ -120,8 +120,9 @@ module.exports = function(Role) { /** * Add custom handler for roles. * @param {String} role Name of role. - * @param {Function} resolver Function that determines if a principal is in the specified role. - * Signature must be `function(role, context, callback)` + * @param {Function} resolver Function that determines + * if a principal is in the specified role. + * Should provide a callback or return a promise. */ Role.registerResolver = function(role, resolver) { if (!Role.resolvers) { @@ -289,7 +290,14 @@ module.exports = function(Role) { var resolver = Role.resolvers[role]; if (resolver) { debug('Custom resolver found for role %s', role); - resolver(role, context, callback); + + var promise = resolver(role, context, callback); + if (promise && typeof promise.then === 'function') { + promise.then( + function(result) { callback(null, result); }, + callback + ); + } return; } diff --git a/test/role.test.js b/test/role.test.js index 2129fcb7..8ecddde2 100644 --- a/test/role.test.js +++ b/test/role.test.js @@ -8,6 +8,7 @@ var Application = loopback.Application; var ACL = loopback.ACL; var async = require('async'); var expect = require('chai').expect; +var Promise = require('bluebird'); function checkResult(err, result) { // console.log(err, result); @@ -172,6 +173,14 @@ describe('role model', function() { }); it('should support owner role resolver', function() { + Role.registerResolver('returnPromise', function(role, context) { + return new Promise(function(resolve) { + process.nextTick(function() { + resolve(true); + }); + }); + }); + var Album = ds.createModel('Album', { name: String, userId: Number, @@ -186,10 +195,16 @@ describe('role model', function() { }); User.create({ name: 'Raymond', email: 'x@y.com', password: 'foobar' }, function(err, user) { + Role.isInRole('returnPromise', { principalType: ACL.USER, principalId: user.id }, + function(err, yes) { + assert(!err && yes); + }); + Role.isInRole(Role.AUTHENTICATED, { principalType: ACL.USER, principalId: user.id }, function(err, yes) { assert(!err && yes); }); + Role.isInRole(Role.AUTHENTICATED, { principalType: ACL.USER, principalId: null }, function(err, yes) { assert(!err && !yes);