<commit_before>/*
beer.js
Provides JSON data that represents a list of beers on tap, in firkins, 
and in special bottles for sale at Al's of Hampden in Enola, PA

Copyright (c) 2014

<NAME>

*/

// required modules
var http = require('http'),
		express = require('express'),
		request = require('request'),
		cheerio = require('cheerio'),
		console = require('clim')('beer'),
		mongojs = require('mongojs'),
		utils = require('./utils'),
		responses = require('./responses'),
		converter = require('./converter');

// request options
var listOptions = {
			url: 'http://alsofhampden.com/beer.php'
		},
		searchOptions = {
			url: 'https://api.untappd.com/v4/search/beer',
			json: true,
			qs: {
				client_id: process.env.untappdClientID,
				client_secret: process.env.untappdClientSecret,
				limit: 1
			}
		};

// app bootstrap
var app = express();

/*
 * Search for a beer by brewery + name.
 * Action: GET
 * Params: brewery, the name of the brewery
 *         name, the name of the beer
 */
app.get('/nodejs/beer/search', function (req, res) {
	var result = {};

	if (req.query.brewery && req.query.name) {
		// sanitize the query string input
		var beer = {
			brewery: decodeURIComponent(req.query.brewery),
			name: decodeURIComponent(req.query.name)
		};
		// apply conversions to the beer input
		converter.handle(beer);
		beer.brewery = utils.trim(beer.brewery);
		beer.name = utils.trim(beer.name);

		// get a hook to the database
		var db = mongojs('beer', ['collection']);

		// look up beer in db
		db.collection.findOne({
			brewery: beer.brewery,
			name: beer.name
		}, function(err, doc) {
			// handle exception from query
			if (err) {
				responses.sendError(res, {
					desc: responses.exceptions.databaseError,
					code: 500,
					error: err
				});
				return;
			}

			// if we got a result from the db, write out the record
			if (doc) {
				result = doc;
				result.fetchMethod = 'mongodb';
				responses.sendSuccess(res, result, true);
			} else {
				// if not found, fetch from untappd, store in db, and write out the response
				searchOptions.qs.q = encodeURIComponent(beer.brewery + ' ' + beer.name);

				// fire off request to untappd search api
				request(searchOptions, function (error, response, json) {
					if (!error && response.statusCode === 200) {
						if (json.response.found > 0 && json.response.beers.items.length > 0) {
							result = json.response.beers.items[0].beer;

							// persist to db
							db.collection.save({
								brewery: beer.brewery, 
								name: beer.name, 
								data: result,
								created: Date.now()
							}, function(err, doc) {
								doc.fetchMethod = 'untappd';
								responses.sendSuccess(res, doc, true);
								// log the persisted beer
								console.log('new beer persisted: ' + doc.brewery + ' ' + doc.name);
							});	
						} else {
							responses.sendError(res, {
								desc: response.exceptions.untappdSearchError,
								code: 404,<commit_msg>Error handling bug fix<commit_after>/*
beer.js
Provides JSON data that represents a list of beers on tap, in firkins, 
and in special bottles for sale at Al's of Hampden in Enola, PA

Copyright (c) 2014

<NAME>

*/

// required modules
var http = require('http'),
		express = require('express'),
		request = require('request'),
		cheerio = require('cheerio'),
		console = require('clim')('beer'),
		mongojs = require('mongojs'),
		utils = require('./utils'),
		responses = require('./responses'),
		converter = require('./converter');

// request options
var listOptions = {
			url: 'http://alsofhampden.com/beer.php'
		},
		searchOptions = {
			url: 'https://api.untappd.com/v4/search/beer',
			json: true,
			qs: {
				client_id: process.env.untappdClientID,
				client_secret: process.env.untappdClientSecret,
				limit: 1
			}
		};

// app bootstrap
var app = express();

/*
 * Search for a beer by brewery + name.
 * Action: GET
 * Params: brewery, the name of the brewery
 *         name, the name of the beer
 */
app.get('/nodejs/beer/search', function (req, res) {
	var result = {};

	if (req.query.brewery && req.query.name) {
		// sanitize the query string input
		var beer = {
			brewery: decodeURIComponent(req.query.brewery),
			name: decodeURIComponent(req.query.name)
		};
		// apply conversions to the beer input
		converter.handle(beer);
		beer.brewery = utils.trim(beer.brewery);
		beer.name = utils.trim(beer.name);

		// get a hook to the database
		var db = mongojs('beer', ['collection']);

		// look up beer in db
		db.collection.findOne({
			brewery: beer.brewery,
			name: beer.name
		}, function(err, doc) {
			// handle exception from query
			if (err) {
				responses.sendError(res, {
					desc: responses.exceptions.databaseError,
					code: 500,
					error: err
				});
				return;
			}

			// if we got a result from the db, write out the record
			if (doc) {
				result = doc;
				result.fetchMethod = 'mongodb';
				responses.sendSuccess(res, result, true);
			} else {
				// if not found, fetch from untappd, store in db, and write out the response
				searchOptions.qs.q = encodeURIComponent(beer.brewery + ' ' + beer.name);

				// fire off request to untappd search api
				request(searchOptions, function (error, response, json) {
					if (!error && response.statusCode === 200) {
						if (json.response.found > 0 && json.response.beers.items.length > 0) {
							result = json.response.beers.items[0].beer;

							// persist to db
							db.collection.save({
								brewery: beer.brewery, 
								name: beer.name, 
								data: result,
								created: Date.now()
							}, function(err, doc) {
								doc.fetchMethod = 'untappd';
								responses.sendSuccess(res, doc, true);
								// log the persisted beer
								console.log('new beer persisted: ' + doc.brewery + ' ' + doc.name);
							});	
						} else {
							responses.sendError(res, {
								desc: responses.exceptions.untappdSearchError,
								code: 404,
{'fraction_non_alphanumeric': 0.13634829564630443, 'fraction_numerical': 0.006074924063449207, 'mean_word_length': 2.756020278833967, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '455596', 'n_tokens_mistral': 2424, 'n_tokens_neox': 1937, 'n_words': 524}