Last active
November 10, 2016 00:57
-
-
Save moshmage/f94d100c088eae8547c7a0099ca44216 to your computer and use it in GitHub Desktop.
quick and dirty handshaker between twitter and an application
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
/** | |
* Created by Mosh Mage on 10/14/2016. | |
* quick and dirty handshaker between twitter and an application | |
* this could be loaded by modules, but time if of the essence | |
* todo: module loader, add express, make a decent api | |
*/ | |
"use strict"; | |
var http = require('http'); | |
var request = require('request'); | |
var url = require('url'); | |
var Twitter = require('twitter'); | |
var PORT = process.env.PORT || 3300; | |
var KEY = 'consumer_key'; | |
var SECRET = 'consumer_secret'; | |
var ENCODED = new Buffer(KEY + ':' + SECRET).toString('base64'); | |
var httpServer, tweetClient; | |
function getBearerToken(callback) { | |
request({ | |
uri: 'https://api.twitter.com/oauth2/token', | |
method: 'POST', | |
body: 'grant_type=client_credentials', | |
headers: { | |
'Authorization': 'Basic ' + ENCODED, | |
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' | |
} | |
},function (error, response, body) { | |
console.log(JSON.parse(body).access_token); | |
tweetClient = new Twitter({ | |
consumer_key: KEY, | |
consumer_secret: SECRET, | |
bearer_token: JSON.parse(body).access_token | |
}); | |
callback(body); | |
}); | |
} | |
function createServer() { | |
httpServer = http.createServer(function(req, res) { | |
var method = req.method || false; | |
var pathName = url.parse(req.url).pathname || false; | |
var query = {}; | |
res.setHeader('Access-Control-Allow-Origin', '*'); | |
res.setHeader('Access-Control-Request-Method', '*'); | |
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET'); | |
res.setHeader('Access-Control-Allow-Headers', '*'); | |
console.log('->',req.method,url.parse(req.url).pathname); | |
if (method && pathName) { | |
if (method === 'GET') { | |
if (pathName == '/tweets/') { | |
query = url.parse(req.url,true).query; | |
tweetClient.get('search/tweets', | |
{q: query.q || '', max_id: query.max_id || '', include_entities: query.include_entities || '', | |
count: (query.count) ? parseInt(query.count,10) : 15}, | |
function (error, tweets, response) { | |
res.write(JSON.stringify(tweets)); | |
res.end(); | |
} | |
); | |
} | |
} | |
} | |
}); | |
httpServer.listen(PORT, function () { console.log('UP!', PORT)}); | |
} | |
getBearerToken(createServer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment