Last active
August 3, 2016 17:28
-
-
Save noahcoad/d14d0ede5917ec186c8b87c7bdbe89ba to your computer and use it in GitHub Desktop.
ManPow Homeland Hubspot Proxy hook.io
This file contains hidden or 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
module['exports'] = function echoHttp (hook) { | |
var request = require('request'); | |
var mongodb = require('mongodb'); | |
paths = { | |
'requestbin': hook.env['manpow-homeland-hubspot-proxy-requestbin-url'], | |
'moneybug': "http://homeland2.nwaoftexas.com/hubspot/money-bug-hook", | |
'nwa': 'https://homeland.nwaoftexas.com/nwa/import/investor-lead-data', | |
'testnwa': 'http://heartland.nwaoftexas.com/money-bug/collect-newwestern', | |
'testmb': "http://heartland.nwaoftexas.com/money-bug/collect" } | |
prefix = "/techadmin-manpow-com/homeland-hubspot-proxy/" | |
path = hook.req.path.substring(prefix.length) | |
console.log('run at ', path); | |
constr = hook.env['manpow-homeland-hubspot-proxy-mongodb-constr'] | |
var MongoClient = mongodb.MongoClient; | |
MongoClient.connect(constr, function (err, db) { | |
if (err) console.log('Unable to connect to the mongoDB server. Error:', err); | |
else { | |
// save this post body | |
doc = {inserted: new Date(), path: path, body: hook.params, repost: []} | |
db.collection('posts').insert(doc, {w: 1, fullResult: true}, function(err, recs){ | |
if (err) throw err; | |
var id = recs.ops[0]._id; | |
// if this is a known path to re-post to | |
var stamp = new Date(); | |
if (path in paths) { | |
var url = paths[path] | |
var options = { uri: url, method: 'POST', json: hook.params, timeout: 60 * 1000 }; | |
request(options, function (err, res, body) { | |
var success = (!err && (res.statusCode == 200 || res.statusCode == 201)); | |
var doc = { '$push': { repost: { statusCode: res.statusCode, attempted: new Date(), to: url, seconds: ((new Date()) - stamp)/1000, success: success } } }; | |
if (!success) doc.err = err; | |
db.collection('posts').update( { '_id': id }, doc, | |
function(err, records) { | |
if (err) throw err; | |
db.close(); | |
hook.res.end("done"); | |
}); | |
// if not successful, try again here | |
}); | |
} | |
else { | |
var doc = { '$push': { repost: { attempted: new Date(), seconds: ((new Date()) - stamp)/1000, success: false, error: "path not found to repost to", post_path: path } } }; | |
db.collection('posts').update( { '_id': id }, doc, | |
function(err, records) { | |
if (err) throw err; | |
db.close(); | |
hook.res.end("done"); | |
}); | |
} | |
}); | |
} | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment