API code cleanup

This commit is contained in:
Sahat Yalkabov
2014-10-27 19:58:38 -07:00
parent 656591f3c3
commit 4cff300afa

View File

@ -37,7 +37,6 @@ exports.getApi = function(req, res) {
exports.getFoursquare = function(req, res, next) { exports.getFoursquare = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'foursquare' }); var token = _.find(req.user.tokens, { kind: 'foursquare' });
console.log(token);
async.parallel({ async.parallel({
trendingVenues: function(callback) { trendingVenues: function(callback) {
foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) { foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) {
@ -71,7 +70,7 @@ exports.getFoursquare = function(req, res, next) {
* Tumblr API example. * Tumblr API example.
*/ */
exports.getTumblr = function(req, res) { exports.getTumblr = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'tumblr' }); var token = _.find(req.user.tokens, { kind: 'tumblr' });
var client = tumblr.createClient({ var client = tumblr.createClient({
consumer_key: secrets.tumblr.consumerKey, consumer_key: secrets.tumblr.consumerKey,
@ -80,6 +79,7 @@ exports.getTumblr = function(req, res) {
token_secret: token.tokenSecret token_secret: token.tokenSecret
}); });
client.posts('withinthisnightmare.tumblr.com', { type: 'photo' }, function(err, data) { client.posts('withinthisnightmare.tumblr.com', { type: 'photo' }, function(err, data) {
if (err) return next(err);
res.render('api/tumblr', { res.render('api/tumblr', {
title: 'Tumblr API', title: 'Tumblr API',
blog: data.blog, blog: data.blog,
@ -128,7 +128,7 @@ exports.getScraping = function(req, res, next) {
if (err) return next(err); if (err) return next(err);
var $ = cheerio.load(body); var $ = cheerio.load(body);
var links = []; var links = [];
$(".title a[href^='http'], a[href^='https']").each(function() { $('.title a[href^="http"], a[href^="https"]').each(function() {
links.push($(this)); links.push($(this));
}); });
res.render('api/scraping', { res.render('api/scraping', {
@ -142,11 +142,13 @@ exports.getScraping = function(req, res, next) {
* GET /api/github * GET /api/github
* GitHub API Example. * GitHub API Example.
*/ */
exports.getGithub = function(req, res) {
exports.getGithub = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'github' }); var token = _.find(req.user.tokens, { kind: 'github' });
var github = new Github({ token: token.accessToken }); var github = new Github({ token: token.accessToken });
var repo = github.getRepo('sahat', 'requirejs-library'); var repo = github.getRepo('sahat', 'requirejs-library');
repo.show(function(err, repo) { repo.show(function(err, repo) {
if (err) return next(err);
res.render('api/github', { res.render('api/github', {
title: 'GitHub API', title: 'GitHub API',
repo: repo repo: repo
@ -174,7 +176,8 @@ exports.getAviary = function(req, res) {
exports.getNewYorkTimes = function(req, res, next) { exports.getNewYorkTimes = function(req, res, next) {
var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' }); var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' });
var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query; var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query;
request.get(url, function(error, request, body) { request.get(url, function(err, request, body) {
if (err) return next(err);
if (request.statusCode === 403) return next(Error('Missing or Invalid New York Times API Key')); if (request.statusCode === 403) return next(Error('Missing or Invalid New York Times API Key'));
var bestsellers = JSON.parse(body); var bestsellers = JSON.parse(body);
res.render('api/nyt', { res.render('api/nyt', {
@ -194,7 +197,7 @@ exports.getLastfm = function(req, res, next) {
async.parallel({ async.parallel({
artistInfo: function(done) { artistInfo: function(done) {
lastfm.request('artist.getInfo', { lastfm.request('artist.getInfo', {
artist: 'Sirenia', artist: 'The Pierces',
handlers: { handlers: {
success: function(data) { success: function(data) {
done(null, data); done(null, data);
@ -207,7 +210,7 @@ exports.getLastfm = function(req, res, next) {
}, },
artistTopTracks: function(done) { artistTopTracks: function(done) {
lastfm.request('artist.getTopTracks', { lastfm.request('artist.getTopTracks', {
artist: 'Sirenia', artist: 'The Pierces',
handlers: { handlers: {
success: function(data) { success: function(data) {
var tracks = []; var tracks = [];
@ -224,7 +227,7 @@ exports.getLastfm = function(req, res, next) {
}, },
artistTopAlbums: function(done) { artistTopAlbums: function(done) {
lastfm.request('artist.getTopAlbums', { lastfm.request('artist.getTopAlbums', {
artist: 'Sirenia', artist: 'The Pierces',
handlers: { handlers: {
success: function(data) { success: function(data) {
var albums = []; var albums = [];
@ -283,19 +286,16 @@ exports.getTwitter = function(req, res, next) {
/** /**
* POST /api/twitter * POST /api/twitter
* @param tweet * Post a tweet.
*/ */
exports.postTwitter = function(req, res, next) { exports.postTwitter = function(req, res, next) {
req.assert('tweet', 'Tweet cannot be empty.').notEmpty(); req.assert('tweet', 'Tweet cannot be empty.').notEmpty();
var errors = req.validationErrors(); var errors = req.validationErrors();
if (errors) { if (errors) {
req.flash('errors', errors); req.flash('errors', errors);
return res.redirect('/api/twitter'); return res.redirect('/api/twitter');
} }
var token = _.find(req.user.tokens, { kind: 'twitter' }); var token = _.find(req.user.tokens, { kind: 'twitter' });
var T = new Twit({ var T = new Twit({
consumer_key: secrets.twitter.consumerKey, consumer_key: secrets.twitter.consumerKey,
@ -304,6 +304,7 @@ exports.postTwitter = function(req, res, next) {
access_token_secret: token.tokenSecret access_token_secret: token.tokenSecret
}); });
T.post('statuses/update', { status: req.body.tweet }, function(err, data, response) { T.post('statuses/update', { status: req.body.tweet }, function(err, data, response) {
if (err) return next(err);
req.flash('success', { msg: 'Tweet has been posted.'}); req.flash('success', { msg: 'Tweet has been posted.'});
res.redirect('/api/twitter'); res.redirect('/api/twitter');
}); });
@ -317,7 +318,6 @@ exports.postTwitter = function(req, res, next) {
exports.getSteam = function(req, res, next) { exports.getSteam = function(req, res, next) {
var steamId = '76561197982488301'; var steamId = '76561197982488301';
var query = { l: 'english', steamid: steamId, key: secrets.steam.apiKey }; var query = { l: 'english', steamid: steamId, key: secrets.steam.apiKey };
async.parallel({ async.parallel({
playerAchievements: function(done) { playerAchievements: function(done) {
query.appid = '49520'; query.appid = '49520';
@ -330,18 +330,18 @@ exports.getSteam = function(req, res, next) {
playerSummaries: function(done) { playerSummaries: function(done) {
query.steamids = steamId; query.steamids = steamId;
var qs = querystring.stringify(query); var qs = querystring.stringify(query);
request.get({ url: 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?' + qs, json: true }, function(error, request, body) { request.get({ url: 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?' + qs, json: true }, function(err, request, body) {
if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key')); if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key'));
done(error, body); done(err, body);
}); });
}, },
ownedGames: function(done) { ownedGames: function(done) {
query.include_appinfo = 1; query.include_appinfo = 1;
query.include_played_free_games = 1; query.include_played_free_games = 1;
var qs = querystring.stringify(query); var qs = querystring.stringify(query);
request.get({ url: 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?' + qs, json: true }, function(error, request, body) { request.get({ url: 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?' + qs, json: true }, function(err, request, body) {
if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key')); if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key'));
done(error, body); done(err, body);
}); });
} }
}, },
@ -370,14 +370,12 @@ exports.getStripe = function(req, res) {
/** /**
* POST /api/stripe * POST /api/stripe
* @param stipeToken * Make a payment.
* @param stripeEmail
*/ */
exports.postStripe = function(req, res, next) { exports.postStripe = function(req, res, next) {
var stripeToken = req.body.stripeToken; var stripeToken = req.body.stripeToken;
var stripeEmail = req.body.stripeEmail; var stripeEmail = req.body.stripeEmail;
stripe.charges.create({ stripe.charges.create({
amount: 395, amount: 395,
currency: 'usd', currency: 'usd',
@ -406,28 +404,22 @@ exports.getTwilio = function(req, res) {
/** /**
* POST /api/twilio * POST /api/twilio
* Twilio API example. * Send a text message using Twilio.
* @param number
* @param message
*/ */
exports.postTwilio = function(req, res, next) { exports.postTwilio = function(req, res, next) {
req.assert('number', 'Phone number is required.').notEmpty(); req.assert('number', 'Phone number is required.').notEmpty();
req.assert('message', 'Message cannot be blank.').notEmpty(); req.assert('message', 'Message cannot be blank.').notEmpty();
var errors = req.validationErrors(); var errors = req.validationErrors();
if (errors) { if (errors) {
req.flash('errors', errors); req.flash('errors', errors);
return res.redirect('/api/twilio'); return res.redirect('/api/twilio');
} }
var message = { var message = {
to: req.body.number, to: req.body.number,
from: '+13472235148', from: '+13472235148',
body: req.body.message body: req.body.message
}; };
twilio.sendMessage(message, function(err, responseData) { twilio.sendMessage(message, function(err, responseData) {
if (err) return next(err.message); if (err) return next(err.message);
req.flash('success', { msg: 'Text sent to ' + responseData.to + '.'}); req.flash('success', { msg: 'Text sent to ' + responseData.to + '.'});
@ -448,8 +440,7 @@ exports.getClockwork = function(req, res) {
/** /**
* POST /api/clockwork * POST /api/clockwork
* Clockwork SMS API example. * Send a text message using Clockwork SMS
* @param telephone
*/ */
exports.postClockwork = function(req, res, next) { exports.postClockwork = function(req, res, next) {
@ -473,7 +464,6 @@ exports.postClockwork = function(req, res, next) {
exports.getVenmo = function(req, res, next) { exports.getVenmo = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'venmo' }); var token = _.find(req.user.tokens, { kind: 'venmo' });
var query = querystring.stringify({ access_token: token.accessToken }); var query = querystring.stringify({ access_token: token.accessToken });
async.parallel({ async.parallel({
getProfile: function(done) { getProfile: function(done) {
request.get({ url: 'https://api.venmo.com/v1/me?' + query, json: true }, function(err, request, body) { request.get({ url: 'https://api.venmo.com/v1/me?' + query, json: true }, function(err, request, body) {
@ -483,7 +473,6 @@ exports.getVenmo = function(req, res, next) {
getRecentPayments: function(done) { getRecentPayments: function(done) {
request.get({ url: 'https://api.venmo.com/v1/payments?' + query, json: true }, function(err, request, body) { request.get({ url: 'https://api.venmo.com/v1/payments?' + query, json: true }, function(err, request, body) {
done(err, body); done(err, body);
}); });
} }
}, },
@ -499,9 +488,6 @@ exports.getVenmo = function(req, res, next) {
/** /**
* POST /api/venmo * POST /api/venmo
* @param user
* @param note
* @param amount
* Send money. * Send money.
*/ */
@ -509,22 +495,17 @@ exports.postVenmo = function(req, res, next) {
req.assert('user', 'Phone, Email or Venmo User ID cannot be blank').notEmpty(); req.assert('user', 'Phone, Email or Venmo User ID cannot be blank').notEmpty();
req.assert('note', 'Please enter a message to accompany the payment').notEmpty(); req.assert('note', 'Please enter a message to accompany the payment').notEmpty();
req.assert('amount', 'The amount you want to pay cannot be blank').notEmpty(); req.assert('amount', 'The amount you want to pay cannot be blank').notEmpty();
var errors = req.validationErrors(); var errors = req.validationErrors();
if (errors) { if (errors) {
req.flash('errors', errors); req.flash('errors', errors);
return res.redirect('/api/venmo'); return res.redirect('/api/venmo');
} }
var token = _.find(req.user.tokens, { kind: 'venmo' }); var token = _.find(req.user.tokens, { kind: 'venmo' });
var formData = { var formData = {
access_token: token.accessToken, access_token: token.accessToken,
note: req.body.note, note: req.body.note,
amount: req.body.amount amount: req.body.amount
}; };
if (validator.isEmail(req.body.user)) { if (validator.isEmail(req.body.user)) {
formData.email = req.body.user; formData.email = req.body.user;
} else if (validator.isNumeric(req.body.user) && } else if (validator.isNumeric(req.body.user) &&
@ -533,7 +514,6 @@ exports.postVenmo = function(req, res, next) {
} else { } else {
formData.user_id = req.body.user; formData.user_id = req.body.user;
} }
request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) { request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) {
if (err) return next(err); if (err) return next(err);
if (request.statusCode !== 200) { if (request.statusCode !== 200) {
@ -553,7 +533,6 @@ exports.postVenmo = function(req, res, next) {
exports.getLinkedin = function(req, res, next) { exports.getLinkedin = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'linkedin' }); var token = _.find(req.user.tokens, { kind: 'linkedin' });
var linkedin = Linkedin.init(token.accessToken); var linkedin = Linkedin.init(token.accessToken);
linkedin.people.me(function(err, $in) { linkedin.people.me(function(err, $in) {
if (err) return next(err); if (err) return next(err);
res.render('api/linkedin', { res.render('api/linkedin', {
@ -570,10 +549,8 @@ exports.getLinkedin = function(req, res, next) {
exports.getInstagram = function(req, res, next) { exports.getInstagram = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'instagram' }); var token = _.find(req.user.tokens, { kind: 'instagram' });
ig.use({ client_id: secrets.instagram.clientID, client_secret: secrets.instagram.clientSecret }); ig.use({ client_id: secrets.instagram.clientID, client_secret: secrets.instagram.clientSecret });
ig.use({ access_token: token.accessToken }); ig.use({ access_token: token.accessToken });
async.parallel({ async.parallel({
searchByUsername: function(done) { searchByUsername: function(done) {
ig.user_search('richellemead', function(err, users, limit) { ig.user_search('richellemead', function(err, users, limit) {
@ -611,6 +588,7 @@ exports.getInstagram = function(req, res, next) {
* GET /api/yahoo * GET /api/yahoo
* Yahoo API example. * Yahoo API example.
*/ */
exports.getYahoo = function(req, res) { exports.getYahoo = function(req, res) {
Y.YQL('SELECT * FROM weather.forecast WHERE (location = 10007)', function(response) { Y.YQL('SELECT * FROM weather.forecast WHERE (location = 10007)', function(response) {
var location = response.query.results.channel.location; var location = response.query.results.channel.location;