Skip to content

Commit

Permalink
Update mailchimp to request + error handling++
Browse files Browse the repository at this point in the history
  • Loading branch information
bnoguchi committed Apr 22, 2012
1 parent 543c8bb commit c88884f
Showing 1 changed file with 46 additions and 22 deletions.
68 changes: 46 additions & 22 deletions lib/modules/mailchimp.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var oauthModule = require('./oauth2'),
rest = require('../restler');
var oauthModule = require('./oauth2')
, request = require('request');

var mailchimp = module.exports =
oauthModule.submodule('mailchimp')
Expand All @@ -14,30 +14,54 @@ oauthModule.submodule('mailchimp')
.entryPath('/auth/mailchimp')
.callbackPath('/auth/mailchimp/callback')
.fetchOAuthUser( function (accessToken) {
var p = this.Promise();
var promise = this.Promise();
this.oauth._request("GET", this.oauthHost() + this.metadataPath(), {
Authorization: 'OAuth ' + accessToken
},"","",function(error,data){
if (error) return p.fail(error);

var metadata = JSON.parse(data);
var apikey = accessToken + "-"+ metadata.dc;

rest.post(metadata.api_endpoint + '/1.3/?method=getAccountDetails',
{data:{apikey: apikey}})

.on('success',function(user,response){
user.apikey = apikey;
p.fulfill(user);
})

.on('error',function(err){
p.fail(err);
},"","", function (err,data){
if (err) return promise.fail(err);

var metadata = JSON.parse(data)
, apikey = accessToken + "-"+ metadata.dc;

request.post({
url: metadata.api_endpoint + '/1.3/?method=getAccountDetails'
, form: {apikey: apikey}
}, function (err, body, res) {
if (err) {
err.extra = {res: res, data: body};
return promise.fail(err);
}
if (parseInt(res.statusCode/100, 10) !== 2) {
return promise.fail({extra: {data: body, res: res}});
}
var oauthUser = JSON.parse(body);
oauthUser.apikey = apikey;
return promise.fulfill(oauthUser);
});
});

return p;
return promise;
})
.postAccessTokenParamsVia("data")
.authQueryParam('response_type','code')
.accessTokenParam('grant_type','authorization_code')
.accessTokenParam('grant_type','authorization_code')

.moduleErrback( function (err, seqValues) {
if (err instanceof Error) {
var next = seqValues.next;
return next(err);
} else if (err.extra) {
var mailchimpResponse = err.extra.res
, serverResponse = seqValues.res;
serverResponse.writeHead(
mailchimpResponse.statusCode
, mailchimpResponse.headers);
serverResponse.end(err.extra.data);
} else if (err.statusCode) {
var serverResponse = seqValues.res;
serverResponse.writeHead(err.statusCode);
serverResponse.end(err.data);
} else {
console.error(err);
throw new Error('Unsupported error type');
}
});

0 comments on commit c88884f

Please sign in to comment.