Skip to content

Commit

Permalink
API code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
sahat committed Oct 28, 2014
1 parent 01e7bd5 commit cdbb9d1
Showing 1 changed file with 23 additions and 45 deletions.
68 changes: 23 additions & 45 deletions controllers/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ exports.getApi = function(req, res) {

exports.getFoursquare = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'foursquare' });
console.log(token);
async.parallel({
trendingVenues: function(callback) {
foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) {
Expand Down Expand Up @@ -71,7 +70,7 @@ exports.getFoursquare = function(req, res, next) {
* Tumblr API example.
*/

exports.getTumblr = function(req, res) {
exports.getTumblr = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'tumblr' });
var client = tumblr.createClient({
consumer_key: secrets.tumblr.consumerKey,
Expand All @@ -80,6 +79,7 @@ exports.getTumblr = function(req, res) {
token_secret: token.tokenSecret
});
client.posts('withinthisnightmare.tumblr.com', { type: 'photo' }, function(err, data) {
if (err) return next(err);
res.render('api/tumblr', {
title: 'Tumblr API',
blog: data.blog,
Expand Down Expand Up @@ -128,7 +128,7 @@ exports.getScraping = function(req, res, next) {
if (err) return next(err);
var $ = cheerio.load(body);
var links = [];
$(".title a[href^='http'], a[href^='https']").each(function() {
$('.title a[href^="http"], a[href^="https"]').each(function() {
links.push($(this));
});
res.render('api/scraping', {
Expand All @@ -142,11 +142,13 @@ exports.getScraping = function(req, res, next) {
* GET /api/github
* GitHub API Example.
*/
exports.getGithub = function(req, res) {

exports.getGithub = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'github' });
var github = new Github({ token: token.accessToken });
var repo = github.getRepo('sahat', 'requirejs-library');
repo.show(function(err, repo) {
if (err) return next(err);
res.render('api/github', {
title: 'GitHub API',
repo: repo
Expand Down Expand Up @@ -174,7 +176,8 @@ exports.getAviary = function(req, res) {
exports.getNewYorkTimes = function(req, res, next) {
var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' });
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'));
var bestsellers = JSON.parse(body);
res.render('api/nyt', {
Expand All @@ -194,7 +197,7 @@ exports.getLastfm = function(req, res, next) {
async.parallel({
artistInfo: function(done) {
lastfm.request('artist.getInfo', {
artist: 'Sirenia',
artist: 'The Pierces',
handlers: {
success: function(data) {
done(null, data);
Expand All @@ -207,7 +210,7 @@ exports.getLastfm = function(req, res, next) {
},
artistTopTracks: function(done) {
lastfm.request('artist.getTopTracks', {
artist: 'Sirenia',
artist: 'The Pierces',
handlers: {
success: function(data) {
var tracks = [];
Expand All @@ -224,7 +227,7 @@ exports.getLastfm = function(req, res, next) {
},
artistTopAlbums: function(done) {
lastfm.request('artist.getTopAlbums', {
artist: 'Sirenia',
artist: 'The Pierces',
handlers: {
success: function(data) {
var albums = [];
Expand Down Expand Up @@ -283,19 +286,16 @@ exports.getTwitter = function(req, res, next) {

/**
* POST /api/twitter
* @param tweet
* Post a tweet.
*/

exports.postTwitter = function(req, res, next) {
req.assert('tweet', 'Tweet cannot be empty.').notEmpty();

var errors = req.validationErrors();

if (errors) {
req.flash('errors', errors);
return res.redirect('/api/twitter');
}

var token = _.find(req.user.tokens, { kind: 'twitter' });
var T = new Twit({
consumer_key: secrets.twitter.consumerKey,
Expand All @@ -304,6 +304,7 @@ exports.postTwitter = function(req, res, next) {
access_token_secret: token.tokenSecret
});
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.'});
res.redirect('/api/twitter');
});
Expand All @@ -317,7 +318,6 @@ exports.postTwitter = function(req, res, next) {
exports.getSteam = function(req, res, next) {
var steamId = '76561197982488301';
var query = { l: 'english', steamid: steamId, key: secrets.steam.apiKey };

async.parallel({
playerAchievements: function(done) {
query.appid = '49520';
Expand All @@ -330,18 +330,18 @@ exports.getSteam = function(req, res, next) {
playerSummaries: function(done) {
query.steamids = steamId;
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'));
done(error, body);
done(err, body);
});
},
ownedGames: function(done) {
query.include_appinfo = 1;
query.include_played_free_games = 1;
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'));
done(error, body);
done(err, body);
});
}
},
Expand Down Expand Up @@ -370,25 +370,23 @@ exports.getStripe = function(req, res) {

/**
* POST /api/stripe
* @param stipeToken
* @param stripeEmail
* Make a payment.
*/

exports.postStripe = function(req, res, next) {
var stripeToken = req.body.stripeToken;
var stripeEmail = req.body.stripeEmail;

stripe.charges.create({
amount: 395,
currency: 'usd',
card: stripeToken,
description: stripeEmail
}, function(err, charge) {
if (err && err.type === 'StripeCardError') {
req.flash('errors', { msg: 'Your card has been declined.'});
req.flash('errors', { msg: 'Your card has been declined.' });
res.redirect('/api/stripe');
}
req.flash('success', { msg: 'Your card has been charged successfully.'});
req.flash('success', { msg: 'Your card has been charged successfully.' });
res.redirect('/api/stripe');
});
};
Expand All @@ -406,28 +404,22 @@ exports.getTwilio = function(req, res) {

/**
* POST /api/twilio
* Twilio API example.
* @param number
* @param message
* Send a text message using Twilio.
*/

exports.postTwilio = function(req, res, next) {
req.assert('number', 'Phone number is required.').notEmpty();
req.assert('message', 'Message cannot be blank.').notEmpty();

var errors = req.validationErrors();

if (errors) {
req.flash('errors', errors);
return res.redirect('/api/twilio');
}

var message = {
to: req.body.number,
from: '+13472235148',
body: req.body.message
};

twilio.sendMessage(message, function(err, responseData) {
if (err) return next(err.message);
req.flash('success', { msg: 'Text sent to ' + responseData.to + '.'});
Expand All @@ -448,8 +440,7 @@ exports.getClockwork = function(req, res) {

/**
* POST /api/clockwork
* Clockwork SMS API example.
* @param telephone
* Send a text message using Clockwork SMS
*/

exports.postClockwork = function(req, res, next) {
Expand All @@ -473,7 +464,6 @@ exports.postClockwork = function(req, res, next) {
exports.getVenmo = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'venmo' });
var query = querystring.stringify({ access_token: token.accessToken });

async.parallel({
getProfile: function(done) {
request.get({ url: 'https://api.venmo.com/v1/me?' + query, json: true }, function(err, request, body) {
Expand All @@ -483,7 +473,6 @@ exports.getVenmo = function(req, res, next) {
getRecentPayments: function(done) {
request.get({ url: 'https://api.venmo.com/v1/payments?' + query, json: true }, function(err, request, body) {
done(err, body);

});
}
},
Expand All @@ -499,32 +488,24 @@ exports.getVenmo = function(req, res, next) {

/**
* POST /api/venmo
* @param user
* @param note
* @param amount
* Send money.
*/

exports.postVenmo = function(req, res, next) {
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('amount', 'The amount you want to pay cannot be blank').notEmpty();

var errors = req.validationErrors();

if (errors) {
req.flash('errors', errors);
return res.redirect('/api/venmo');
}

var token = _.find(req.user.tokens, { kind: 'venmo' });

var formData = {
access_token: token.accessToken,
note: req.body.note,
amount: req.body.amount
};

if (validator.isEmail(req.body.user)) {
formData.email = req.body.user;
} else if (validator.isNumeric(req.body.user) &&
Expand All @@ -533,7 +514,6 @@ exports.postVenmo = function(req, res, next) {
} else {
formData.user_id = req.body.user;
}

request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) {
if (err) return next(err);
if (request.statusCode !== 200) {
Expand All @@ -553,7 +533,6 @@ exports.postVenmo = function(req, res, next) {
exports.getLinkedin = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'linkedin' });
var linkedin = Linkedin.init(token.accessToken);

linkedin.people.me(function(err, $in) {
if (err) return next(err);
res.render('api/linkedin', {
Expand All @@ -570,10 +549,8 @@ exports.getLinkedin = function(req, res, next) {

exports.getInstagram = function(req, res, next) {
var token = _.find(req.user.tokens, { kind: 'instagram' });

ig.use({ client_id: secrets.instagram.clientID, client_secret: secrets.instagram.clientSecret });
ig.use({ access_token: token.accessToken });

async.parallel({
searchByUsername: function(done) {
ig.user_search('richellemead', function(err, users, limit) {
Expand Down Expand Up @@ -611,6 +588,7 @@ exports.getInstagram = function(req, res, next) {
* GET /api/yahoo
* Yahoo API example.
*/

exports.getYahoo = function(req, res) {
Y.YQL('SELECT * FROM weather.forecast WHERE (location = 10007)', function(response) {
var location = response.query.results.channel.location;
Expand Down

0 comments on commit cdbb9d1

Please sign in to comment.