diff --git a/README.md b/README.md index 9b46cd5..e1aad0e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ instagram-node ============== NodeJS driver for the Instagram API. -In production at http://totems.co aggregating more than 200 data points per seconds ## Installation @@ -58,7 +57,7 @@ second method, ```authorize_user```, can be used to retrieve and set an access t for a user, allowing your app to act fully on his/her behalf. This method takes three parameters: a ```response_code``` which is sent as a GET parameter once a user has authorized your app and instagram has redirected them back to your -authorization redirect URI, a ```redirect_uri``` which is the same one +authorization redirect URI, a ```redirect_uri``` which is the same one supplied to ```get_authorization_url```, and a callback that takes two parameters ```err``` and ```result```. ```err``` will be populated if and only if the request to authenticate the user has failed for some reason. @@ -252,6 +251,28 @@ or just one with this: ig.del_subscription({ id: 1 }, function(err, subscriptions, remaining, limit){}); ``` +## Promises + +All methods can be used as promises instead of using callbacks, if `.promisify()` is called (this changes all methods signatures and they no longer require a callback to be passed.) Example: + +```javascript +api.use({ + client_id: YOUR_CLIENT_ID, + client_secret: YOUR_CLIENT_SECRET +}); + +api.promisify(); + +app.get('/', function (req, res) { + // BEFORE: + // api.user_media_recent('30739527', function (err, result) { + // res.send(JSON.stringify(result)); + // }); + + // AFTER: + api.user_media_recent('30739527').then(JSON.stringify).then(res.send.bind(res)); +}); +``` ## Errors diff --git a/lib/instagram.js b/lib/instagram.js index 77cdba1..0b21607 100644 --- a/lib/instagram.js +++ b/lib/instagram.js @@ -102,7 +102,36 @@ var instagram = function(spec, my) { var sign_request; /* sign_request(endpoint, params, client_secret); */ var sort_object; /* sort_object(params); */ - var that = {}; + var that = { + promisify: function () { + var api = this; + + Object.keys(api).forEach(function (key) { + if (key === 'promisify' || key === 'get_authorization_url' || key === 'use') { + return false; + } + + var oldFn = api[key]; + api[key] = function () { + var context = this, + args = Array.prototype.slice.call(arguments); + + return new Promise(function (fulfill, reject) { + args.push(function (err) { + if (err) { + reject(err); + } else { + Array.prototype.shift.call(arguments); + fulfill.apply(null, arguments); + } + }); + + oldFn.apply(null, args); + }); + }; + }); + } + }; /*******************************/ /* Private helpers */