Skip to content

Instantly share code, notes, and snippets.

@wreckah
Created September 21, 2016 17:52
Show Gist options
  • Save wreckah/025e9b3df524c9ed70c98c7a76fe9916 to your computer and use it in GitHub Desktop.
Save wreckah/025e9b3df524c9ed70c98c7a76fe9916 to your computer and use it in GitHub Desktop.
const _ = require('lodash');
const config = require('config');
const debug = require('debug')('intercom');
const request = require('request').defaults({
'auth': {
user: config.intercom.access_token,
pass: '',
sendImmediately: true
},
headers: {
'User-Agent': 'SwiftGift',
Accept: 'application/json',
},
json: true,
gzip: true
});
const API_URL = 'https://api.intercom.io/';
const RESEND_TIMEOUT = 5000; // 5 seconds.
const MAX_ATTEMPTS = 3;
function req(method, resourceOrUrl, data, cb) {
let url;
if (resourceOrUrl.startsWith('http'))
url = resourceOrUrl;
else
url = API_URL + resourceOrUrl;
if (_.isFunction(data)) {
cb = data;
data = null;
}
let opts = {};
if (method === 'post' || method === 'put') {
opts.body = data || {};
}
debug(`Send ${method} to ${url}`);
request[method](url, opts, (err, resp, body) => {
debug(`Got ${err || resp.statusCode}`);
if (resp.statusCode === 429) {
// Cutted by Intercom's throttling, re-schedule request.
let _this = this && this.attempts ? this : {attempts: 2};
if (_this.attempts > MAX_ATTEMPTS)
return cb(`Got 429 ${MAX_ATTEMPTS} times: ${method} ${url}`);
_this.timeout = (_this.attempts - 1) * RESEND_TIMEOUT;
return setTimeout(
req.bind(_this, method, resourceOrUrl, data, cb), _this.timeout
);
}
if (err) return cb(err);
if (resp.statusCode >= 400)
return cb(body || `Got HTTP status code ${resp.statusCode} without body`);
cb(null, body);
});
}
module.exports = {
updateUser(user, cb) {
req('post', 'users', user, cb);
},
updateUsers(users, cb) {
let data = {items: []};
for (let i=0; i<users.length; i++) {
data.items.push({
method: 'post',
data_type: 'user',
data: users[i]
});
}
req('post', 'bulk/users', data, cb);
},
getUrl(url, cb) {
req('get', url, cb);
}
};
intercom.updateUsers(data, (err, body) => {
if (err) {
this.counter--;
return this.complete(err);
}
this.log(`Bulk job created ${body.id}`);
if (body.state === 'completed') {
this.counter--;
return this.complete(null);
}
setTimeout(
this.checkJob.bind(this, body.links.self),
JOB_TIMEOUT + parseInt(Math.random() * MS, 10)
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment