Last active
August 29, 2015 14:14
-
-
Save der-On/da897d4622a7a38d06d6 to your computer and use it in GitHub Desktop.
promisify geddy models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
/* | |
Usage: | |
require('./promisify_models')(geddy.model); | |
geddy.model.allPromise() | |
.then(function(result) { ... }) | |
.catch(function(err) { throw err; }); | |
var user = geddy.model.User.create({}); | |
geddy.model.User.savePromise(user) | |
.then(function(result) { ... }) | |
.catch(function(err) { throw err; }); | |
*/ | |
function promisify(self, fn, instance) | |
{ | |
return function() { | |
var args = Array.prototype.slice.call(arguments); | |
var origCallback = null; | |
if (instance) { | |
self = args.shift(); | |
} | |
if (typeof args[args.length - 1] === 'function') { | |
origCallback = args.pop(); | |
} | |
return new Promise(function(resolve, reject) { | |
function callback(err, result) { | |
var args = Array.prototype.slice.call(arguments); | |
var err = args.shift(); | |
if (origCallback) origCallback.apply(null, arguments); | |
if (err) { | |
reject(err); | |
return; | |
} | |
resolve.apply(null, args); | |
} | |
args.push(callback); | |
self[fn].apply(self, args); | |
}); | |
} | |
} | |
module.exports = function(model) { | |
Object.keys(model.descriptionRegistry).forEach(function(name) { | |
model[name].allPromise = promisify(model[name], 'all'); | |
model[name].firstPromise = promisify(model[name], 'first'); | |
model[name].countPromise = promisify(model[name], 'count'); | |
model[name].removePromise = promisify(model[name], 'remove'); | |
model[name].savePromise = promisify(model[name], 'save', true); | |
}); | |
}; | |
module.exports.promisify = promisify; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment