Skip to content

Instantly share code, notes, and snippets.

@marr
Created April 3, 2015 20:19
Show Gist options
  • Save marr/97df52cbec3bd13c3f90 to your computer and use it in GitHub Desktop.
Save marr/97df52cbec3bd13c3f90 to your computer and use it in GitHub Desktop.
var util = require('util');
var debug = require('debug')('createFacebookTestUser');
var events = require('events');
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
var CreateFacebookTestUser = function() {
events.EventEmitter.call(this);
};
util.inherits(CreateFacebookTestUser, events.EventEmitter);
var requestAccessToken = function(appSecret, appId) {
return request({
url:'https://graph.facebook.com/oauth/access_token?client_id=' + appId + '&client_secret=' + appSecret + '&grant_type=client_credentials'
}).then(function (args) {
var body = args[1],
token = body.split('=')[1];
if (!token) {
var message = JSON.parse(body).error.message || 'Could not extract token from body: ' + body;
throw new Error(message);
}
return token;
});
};
var createTestUser = function(appId) {
return function(token) {
return request({
method: 'POST',
url: 'https://graph.facebook.com/' + appId + '/accounts/test-users?access_token=' + token,
json: true
});
};
};
CreateFacebookTestUser.prototype.command = function(callback) {
var self = this;
var appSecret = this.client.options.globals.facebookAppSecret,
appId = this.client.options.globals.facebookAppId;
debug('appId: %s', appId);
requestAccessToken(appSecret + 'x', appId)
.catch(function(e) {
self.emit('error', e);
})
.then(createTestUser(appId))
.then(function (user) {
debug('Successfully created %j', user[1]);
if (callback) {
callback.call(self, null, user[1]);
}
self.emit('complete');
}).error(function (err) {
console.error('Exception in CreateFacebookTestUser', err);
// ??? unclear how to error the command
if (callback) {
callback.call(self, err);
}
self.emit('complete');
});
};
module.exports = CreateFacebookTestUser;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment