diff --git a/.gitignore b/.gitignore index 6a770cc8..3124aa0a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,3 @@ .DS_Store -.gitignore node_modules -endpoints/sms.js -endpoints/phone.js -endpoints/phone2.js -endpoints/phone -endpoints/sms -endpoints/closed_endpoints -index.php -docs -config/*.config.json -repos \ No newline at end of file +config/*.config.json \ No newline at end of file diff --git a/config/dev.json.example b/config/dev.json.example new file mode 100644 index 00000000..2a46b7d1 --- /dev/null +++ b/config/dev.json.example @@ -0,0 +1,4 @@ +{ + "host": "localhost", + "port": 3100 +} diff --git a/endpoints/bus/index.js b/endpoints/bus/index.js index 4f83466a..2f94c505 100644 --- a/endpoints/bus/index.js +++ b/endpoints/bus/index.js @@ -1,104 +1,7 @@ -var request = require('request'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + h = require('../../lib/helpers.js'), + app = require('../../server'); -exports.setup = function(server){ - server.post({path: '/bus/search', version: '1.0.0'}, search); -} - -var search = function(req, res, next) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); - res.json(404,{error:"This api endpoint has been closed temporarily, because Bus.is changed it's markup."}); - return next(); -} - -realtime = function(req, res, next){ - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); - - var data = req.params; - - request('http://straeto.is/bitar/bus/livemap/json.jsp', function (error, response, body) { - if(error) { - res.json(500,{error:'Something went wrong',code:3}); - return next(); - } - if(response.statusCode !== 200){ - res.json(500,{error:"Something went wrong code 1",code:4}); - return next(); - } - - try{ - obj = JSON.parse(body); - }catch(error){ - res.json(500,{error:"Something is wrong with the data provided from the data source"}); - return next(); - } - - var activeBusses = [], - requestedBusses = []; - - obj.routes.forEach(function(object, key){ - activeBusses.push(object.id); - }); - - if(data.busses){ //Post busses = 1,2,3,4,5 - requestedBusses = data.busses.split(","); - - for(var i in requestedBusses){ //Prevent requested to busses that are not available - if(activeBusses.indexOf(requestedBusses[i]) == -1){ - requestedBusses.splice(requestedBusses.indexOf(requestedBusses[i]),1); - } - } - }else{ - //No bus was posted, use all active busses - requestedBusses = activeBusses; - } - - objString = requestedBusses.join('%2C'); - - request('http://straeto.is/bitar/bus/livemap/json.jsp?routes='+objString, function (error, response, body) { - - if(error) { - res.json(500,{error:'Something went wrong',code:3}); - return next(); - } - if(response.statusCode !== 200){ - res.json(500,{error:"Something went wrong code 1",code:4}); - return next(); - } - - var data = JSON.parse(body), - routes = data.routes; - - var objRoutes = { - results: [] - }; - routes.forEach(function(route, key){ - - var objRoute = { - busNr: route.id, - busses: [] - }; - route.busses.forEach(function(bus, key){ - - var location = h.ISN93_To_WGS84(bus.X,bus.Y), - oneRoute = { - 'unixTime': Date.parse(bus.TIMESTAMPREAL)/1000, - 'x': location.lat, - 'y': location.lng, - 'from': bus.FROMSTOP, - 'to': bus.TOSTOP - }; - objRoute.busses.push(oneRoute); - - }); - - objRoutes.results.push(objRoute); - }); - - res.json(200,objRoutes) - return next(); - }); - }); -} \ No newline at end of file +app.post('/bus/search', function(req, res) { + return res.json(404,{error:"This api endpoint has been closed, because Bus.is changed it's markup."}); +}); \ No newline at end of file diff --git a/endpoints/bus/realtime.js b/endpoints/bus/realtime.js index 0357d64b..6d65bd86 100644 --- a/endpoints/bus/realtime.js +++ b/endpoints/bus/realtime.js @@ -1,23 +1,19 @@ var h = require('../../lib/helpers.js'), - request = require('request'); + request = require('request'), + app = require('../../server'); -exports.setup = function(server){ - server.post({path: '/bus/realtime', version: '1.0.0'}, realtime); //Old - server.get({path: '/bus/realtime', version: '1.0.0'}, realtime); -} - -var realtime = function(req, res, next){ - var data = req.params; +app.get('/bus/realtime', function(req, res){ + var data = req.query; request('http://straeto.is/bitar/bus/livemap/json.jsp', function (error, response, body) { - if(error || response.statusCode !== 200) { - throw new Error("The bus api is down or refuses to respond"); - } + if(error || response.statusCode !== 200) + return res.json(500,{error:'The bus api is down or refuses to respond'}); + var obj; try{ obj = JSON.parse(body); }catch(error){ - throw new Error("Something is wrong with the data provided from the data source"); + return res.json(500,{error:'Something is wrong with the data provided from the data source'}); } var activeBusses = [], @@ -44,14 +40,13 @@ var realtime = function(req, res, next){ request('http://straeto.is/bitar/bus/livemap/json.jsp?routes='+objString, function (error, response, body) { - if(error || response.statusCode !== 200) { - throw new Error("The bus api is down or refuses to respond"); - } + if(error || response.statusCode !== 200) + return res.json(500,{error:'The bus api is down or refuses to respond'}); try{ var data = JSON.parse(body); }catch(e){ - throw new Error("Something is wrong with the data provided from the data source"); + return res.json(500,{error:'Something is wrong with the data provided from the data source'}); } var routes = data.routes; @@ -84,9 +79,7 @@ var realtime = function(req, res, next){ }); }); - - res.json(200,objRoutes); - return next(); + return res.json(objRoutes); }); }); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/endpoints/bus/search.js b/endpoints/bus/search.js index c0e6bac7..781deb92 100644 --- a/endpoints/bus/search.js +++ b/endpoints/bus/search.js @@ -1,11 +1,8 @@ -app.post({path: '/bus/search', version: '1.0.0'}, function(req,res){ - res.inactive(error: 'This api endpoint has been closed temporarily, because Bus.is changed it's markup.'); -}); //Old -app.get({path: '/bus/search', version: '1.0.0'}, function(req,res){ - res.inactive(error: 'This api endpoint has been closed temporarily, because Bus.is changed it's markup.'); -}); +var app = require('../../server'); -var search = function(req, res, next) { - res.json(404,{error:"This api endpoint has been closed temporarily, because Bus.is changed it's markup."}); - return next(); -} \ No newline at end of file +app.post('/bus/search', function(req,res){ + res.json(404,{error: 'This api endpoint has been closed temporarily, because Bus.is changed it\'s markup.'}); +}); //Old +app.get('/bus/search', function(req,res){ + res.json(404,{error: 'This api endpoint has been closed temporarily, because Bus.is changed it\'s markup.'}); +}); \ No newline at end of file diff --git a/endpoints/bus/tests/integration_test.js b/endpoints/bus/tests/integration_test.js index cf2feeb4..91a3df09 100644 --- a/endpoints/bus/tests/integration_test.js +++ b/endpoints/bus/tests/integration_test.js @@ -1,6 +1,6 @@ -var request = require('request'); -var assert = require('assert'); -var helpers = require('../../../lib/test_helpers.js'); +var request = require('request'), + assert = require('assert'), + helpers = require('../../../lib/test_helpers.js'); describe('bus', function() { this.timeout(0); // this endpoint is slow diff --git a/endpoints/car/index.js b/endpoints/car/index.js index f555559d..e3467177 100644 --- a/endpoints/car/index.js +++ b/endpoints/car/index.js @@ -1,29 +1,20 @@ -var request = require('request'); -var $ = require('jquery'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + $ = require('jquery'), + h = require('../../lib/helpers.js'), + app = require('../../server'); -exports.setup = function(server){ - server.get({path: '/car', version: '1.0.0'}, lookup); - server.post({path: '/car', version: '1.0.0'}, lookup); -} - -var lookup = function(req, res, next){ - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); - - var data = req.params; +app.get('/car', function(req, res){ + var carPlate = req.query.number || req.query.carPlate || ''; - if(!data.number){ - res.json(431,{error:'Please provide a valid number to lookup'}); - return next(); - } + if(!carPlate) + return res.json(431,{error:'Please provide a valid carPlate to lookup'}); request.get({ headers: {'User-Agent': h.browser()}, - url: 'http://ww2.us.is/upplysingar_um_bil?vehinumber='+data.number + url: 'http://ww2.us.is/upplysingar_um_bil?vehinumber='+carPlate }, function(error, response, body){ if(error || response.statusCode !== 200) { - throw new Error("www.us.is refuses to respond or give back data"); + return res.json(500,{error:'www.us.is refuses to respond or give back data'}); } var data = $(body), obj = { results: []}, @@ -53,7 +44,6 @@ var lookup = function(req, res, next){ }); obj.results.push(car); } - res.json(200,obj) - return next(); + return res.json(obj); }); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/endpoints/car/tests/integration_test.js b/endpoints/car/tests/integration_test.js index 254ad48e..124aad64 100644 --- a/endpoints/car/tests/integration_test.js +++ b/endpoints/car/tests/integration_test.js @@ -2,11 +2,11 @@ var request = require('request'); var assert = require('assert'); var helpers = require('../../../lib/test_helpers.js'); -describe('cars', function() { +describe('flight', function() { it("should return an array of objects containing correct fields", function(done) { var fieldsToCheckFor = ["registryNumber","number","factoryNumber","type","subType","color","registeredAt","status","nextCheck","pollution","weight"]; - var params = helpers.testRequestParams("/car", { number: "AA031" }); + var params = helpers.testRequestParams("/car", { carPlate: "AA031" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); - request.post(params, resultHandler); + request.get(params, resultHandler); }); }); diff --git a/endpoints/cinema/index.js b/endpoints/cinema/index.js index c8c49aad..8187b39c 100644 --- a/endpoints/cinema/index.js +++ b/endpoints/cinema/index.js @@ -1,31 +1,23 @@ -var request = require('request'); -var cheerio = require('cheerio'); -var h = require('../../lib/helpers.js'); - -exports.setup = function ( server ) { - server.get({path: '/cinema', version: '1.0.0'}, getMovies); - server.get({path: '/cinema/theaters', version: '1.0.0'}, getTheaters); -}; +var request = require('request'), + cheerio = require('cheerio'), + app = require('../../server'); /** * Fetches movies for show today in Icelandic cinemas. * response - JSON: Movie data within an 'results' array. */ -var getMovies = function (req, res, next) { - res.charSet = 'utf8'; - +app.get('/cinema', function (req, res, next) { var url = 'http://kvikmyndir.is/bio/syningatimar/'; request(url, function (error, response, body) { - if (error) throw new Error( url + ' not responding correctly...' ); + if (error) return res.json(500,{error: url + ' not responding correctly...' }); // Cheerio declared and then attemted to load. var $; - try { $ = cheerio.load( body ); } catch (e) { - throw new Error( 'Could not load the body with cherrio.' ); + return res.json(500,{error:'Could not load the body with cherrio.'}); } // Base object to be added to @@ -79,21 +71,19 @@ var getMovies = function (req, res, next) { }); }); - res.json(200, obj); - return next(); + return res.json(obj); }); -}; +}); /** * Fetches theaters that are showing movies today. * response - JSON: Theater data within an 'results' array. */ -var getTheaters = function (req, res, next) { - res.charSet = 'utf8'; +app.get('/cinema/theaters', function (req, res, next) { var url = 'http://kvikmyndir.is/bio/syningatimar_bio/'; request(url, function (error, response, body) { - if (error) throw new Error( url + ' not responding correctly...' ); + if (error) return res.json(500,{error: url + ' not responding correctly...' }); // Cheerio declared and then attemted to load. var $; @@ -101,7 +91,7 @@ var getTheaters = function (req, res, next) { try { $ = cheerio.load( body ); } catch (e) { - throw new Error( 'Could not load the body with cherrio.' ); + return res.json(500,{error:'Could not load the body with cherrio.'}); } // Base object to be added to @@ -152,7 +142,6 @@ var getTheaters = function (req, res, next) { }); }); - res.json(200, obj); - return next(); + return res.json(obj); }); -}; \ No newline at end of file +}); \ No newline at end of file diff --git a/endpoints/company/index.js b/endpoints/company/index.js index 6c168530..82b073eb 100644 --- a/endpoints/company/index.js +++ b/endpoints/company/index.js @@ -1,37 +1,34 @@ -var request = require('request'); -var $ = require('jquery'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + $ = require('jquery'), + h = require('../../lib/helpers.js'), + app = require('../../server'); $.fn.cleanHtml = function() { return $.trim(this.html().replace(/<(?:.|\n)*?>/gm, '')); }; -exports.setup = function(server){ - server.post({path: '/company', version: '1.0.0'}, lookup); //Old - server.get({path: '/company', version: '1.0.0'}, lookup); -} -var lookup = function(req, res, next){ - +app.get('/company', function(req, res, next){ + var queryString = { - nafn: req.params.name || '', - heimili: req.params.address || '', - kt: req.params.socialnumber || '', - vsknr: req.params.vsknr || '' + nafn: req.query.name || '', + heimili: req.query.address || '', + kt: req.query.socialnumber || '', + vsknr: req.query.vsknr || '' }; - request.get({ + request.get({ headers: {'User-Agent': h.browser()}, url: 'http://www.rsk.is/fyrirtaekjaskra/leit', qs: queryString - }, function(error, response, body){ - if(error || response.statusCode !== 200) { - throw new Error("www.rsk.is refuses to respond or give back data"); + }, function(error, response, body){ + if(error || response.statusCode !== 200) { + return res.json(500,{error:'www.rsk.is refuses to respond or give back data'}); } - var obj = { results: [] }, - data = $(body); + var obj = { results: [] }, + data = $(body); - if(data.find('.resultnote').length == 0){ + if(data.find('.resultnote').length == 0){ var tr = data.find('.boxbody > .nozebra tbody tr:first'); if (tr.length > 0) { var name = data.find('.boxbody > h1').html(), @@ -44,8 +41,8 @@ var lookup = function(req, res, next){ address: tr.find('td').eq(0).cleanHtml() }); } - }else{ - data.find('table tr:not(:first)').each(function() { + }else{ + data.find('table tr:not(:first)').each(function() { var td = $(this).find('td'); var nameRoot = td.eq(1).cleanHtml(); @@ -58,10 +55,9 @@ var lookup = function(req, res, next){ address: td.eq(2).cleanHtml() }); - }); - } - - res.json(200,obj) - return next(); - }); -}; + }); + } + + return res.json(obj); + }); +}); \ No newline at end of file diff --git a/endpoints/company/tests/integration_test.js b/endpoints/company/tests/integration_test.js index cae04211..7fd3a647 100644 --- a/endpoints/company/tests/integration_test.js +++ b/endpoints/company/tests/integration_test.js @@ -11,28 +11,28 @@ describe('company', function() { it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/company", { name: "hagar" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); - request.post(params, resultHandler); + request.get(params, resultHandler); }); }); describe('searching by address', function() { it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/company", { address: "Hagasmára" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); - request.post(params, resultHandler); + request.get(params, resultHandler); }); }); describe('search by socialnumber', function() { it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/company", { socialnumber: "4307003590" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); - request.post(params, resultHandler); + request.get(params, resultHandler); }); }); describe('search by vsknr', function() { it("should return an array of objects containing correct fields", function(done) { var params = helpers.testRequestParams("/company", { vsknr: "78874" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); - request.post(params, resultHandler); + request.get(params, resultHandler); }); }); }); diff --git a/endpoints/currency/arion.js b/endpoints/currency/arion.js index a5071aa7..3e9511e0 100644 --- a/endpoints/currency/arion.js +++ b/endpoints/currency/arion.js @@ -1,12 +1,9 @@ -var request = require('request'); -var moment = require('moment'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + moment = require('moment'), + h = require('../../lib/helpers.js'), + app = require('../../server'); -exports.setup = function(server){ - server.get({path: '/currency/arion', version: '1.0.0'}, getCurrencies); -} - -var getCurrencies = function(req, res, next){ +app.get('/currency/arion', function(req, res){ var toSend = 'm=GetCurrencies&beginDate='+moment().subtract('days', 1).format('YYYY-MM-DD')+'&finalDate='+moment().format('YYYY-MM-DD')+'¤cyType=AlmenntGengi¤ciesAvailable=ISK%2CUSD%2CGBP%2CEUR%2CCAD%2CDKK%2CNOK%2CSEK%2CCHF%2CJPY%2CXDR'; @@ -16,11 +13,11 @@ var getCurrencies = function(req, res, next){ body: toSend }, function(error, response, body){ if(error || response.statusCode !== 200) { - throw new Error("www.arionbanki.is refuses to respond or give back data"); + return res.json(500,{error:'www.arionbanki.is refuses to respond or give back data'}); } var jsonObject = JSON.parse(body), - obj = { results: [] }; + currencies = []; jsonObject.forEach(function(object,i){ var changePer = parseFloat(object.LastValueChange)/parseFloat(object.MidValue), @@ -37,12 +34,9 @@ var getCurrencies = function(req, res, next){ if(currency.changePer == '-0.00') currency.changePer = 0; - obj.results.push(currency) + currencies.push(currency) }); - res.json(200,obj); - return next(); + return res.json({ results: currencies }); }); -}; - -exports.getCurrencies = getCurrencies; +}); \ No newline at end of file diff --git a/endpoints/currency/index.js b/endpoints/currency/index.js index 96028560..1c72f402 100644 --- a/endpoints/currency/index.js +++ b/endpoints/currency/index.js @@ -1,20 +1,13 @@ -var request = require('request'); -var moment = require('moment'); -var $ = require('jquery'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + moment = require('moment') + app = require('../../server'); -exports.setup = function(server){ - server.post({path: '/currency', version: '1.0.0'}, slash); - server.get({path: '/currency', version: '1.0.0'}, slash); -} - -var slash = function(req, res, next){ - var provider = req.params.provider || 'm5'; //m5 determined by a fair dice roll +app.get('/currency', function(req, res){ + var provider = req.query.provider || 'm5'; //m5 determined by a fair dice roll var providers = ['m5', 'arion', 'lb']; if (providers.indexOf(provider) >= 0) { - require('./'+provider+'.js').getCurrencies(req, res, next); + return res.redirect(301,'/currency/'+ provider); } else { - res.json(404,{error:'This provider does not exist',code:2}); - return next(); + return res.json(404,{error:'This provider does not exist',code:2}); } -} +}); diff --git a/endpoints/currency/lb.js b/endpoints/currency/lb.js index 9258327e..b8b3bd73 100644 --- a/endpoints/currency/lb.js +++ b/endpoints/currency/lb.js @@ -1,20 +1,16 @@ -var request = require('request'); -var parseString = require('xml2js').parseString; +var request = require('request'), + parseString = require('xml2js').parseString, + app = require('../../server'); -exports.setup = function(server){ - server.get({path: '/currency/lb', version: '1.0.0'}, getCurrencies); -}; - -var getCurrencies = function(req, res, next){ +app.get('/currency/lb', function(req, res){ // A = Almennt gengi, S = Seðlagengi var type = req.params['type'] || 'A'; request.get({ url: 'http://www.landsbankinn.is/modules/markets/services/XMLGengi.asmx/NyjastaGengiByType?strTegund=' + type }, function(err, response, xml) { - if(err || response.statusCode !== 200) { - throw new Error("www.landsbankinn.is refuses to respond or give back data"); - } + if(err || response.statusCode !== 200) + return res.json(500,{error: 'www.landsbankinn.is refuses to respond or give back data'}); var currencies = []; parseString(xml, { explicitRoot: false }, function(err, result) { @@ -30,11 +26,8 @@ var getCurrencies = function(req, res, next){ changePer: parseFloat((parseFloat(currency.Breyting) / parseFloat(currency.Midgengi)).toFixed(2)) }); } - res.json(200, { results: currencies }); - return next(); + return res.json({ results: currencies }); }); } ); -}; - -exports.getCurrencies = getCurrencies; +}); diff --git a/endpoints/currency/m5.js b/endpoints/currency/m5.js index 4a0be2bf..52de292a 100644 --- a/endpoints/currency/m5.js +++ b/endpoints/currency/m5.js @@ -1,12 +1,9 @@ -var request = require('request'); -var $ = require('jquery'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + $ = require('jquery'), + h = require('../../lib/helpers.js'), + app = require('../../server'); -exports.setup = function(server) { - server.get({path: '/currency/m5', version: '1.0.0'}, getCurrencies); -}; - -var getCurrencies = function (req, res, next) { +app.get('/currency/m5', function (req, res) { var currencyNames = { s: ['USD','DKK','EUR','JPY','CAD','NOK','GBP','CHF','SEK','TWI','XDR','ISK'], l: ['Bandarískur dalur','Dönsk króna','Evra','Japanskt jen','Kanadískur dalur','Norsk króna','Sterlingspund','Svissneskur franki','Sænsk króna','Gengisvísitala','SDR','Íslensk króna'] @@ -17,7 +14,7 @@ var getCurrencies = function (req, res, next) { url: 'http://www.m5.is/?gluggi=gjaldmidlar' }, function(err, response, body) { if(err || response.statusCode !== 200) { - throw new Error("www.m5.is refuses to respond or give back data"); + return res.json(500,{error:'www.m5.is refuses to respond or give back data'}); } var data = $(body), @@ -38,9 +35,6 @@ var getCurrencies = function (req, res, next) { }); }); - res.json(200, { results: currencies }); - return next(); + return res.json({ results: currencies }); }); -}; - -exports.getCurrencies = getCurrencies; +}); \ No newline at end of file diff --git a/endpoints/earthquake/index.js b/endpoints/earthquake/index.js index d22d2484..53c4299c 100644 --- a/endpoints/earthquake/index.js +++ b/endpoints/earthquake/index.js @@ -1,19 +1,17 @@ var request = require('request'), cheerio = require('cheerio'), - browser = require('../../lib/helpers.js').browser; + browser = require('../../lib/helpers.js').browser, + app = require('../../server'); -exports.setup = function ( server ) { - server.get({path: '/earthquake/is', version: '1.0.0'}, getResults); -}; +app.get('/earthquake/is', function (req, res, next) { + getEarthquakes(function(error,body) { + if(error) return res.json(500,{error:error.toString()}); -var getResults = function (req, res, next) { - getEarthquakes(function(body) { - res.json(200, { + return res.json({ results: parseList(body) }); - return next(); }); -}; +}); /* This function only handles the request part and calls callback with @@ -26,14 +24,11 @@ var getEarthquakes = function(callback) { encoding: "binary" // needed for some reason.. defaulting to ISO-8859-1 }; - request(params, function (error, res, body) { - if (error) throw new Error(error); - - if (res.statusCode != 200) { - throw new Error("HTTP error from endpoint, status code " + res.statusCode); - } + request(params, function (error,res, body) { + if (res.statusCode != 200) + return callback(new Error("HTTP error from endpoint, status code " + res.statusCode)); - return callback(body); + return callback(error,body); }); }; diff --git a/endpoints/flight/index.js b/endpoints/flight/index.js index a3fdb411..4d0d26b8 100644 --- a/endpoints/flight/index.js +++ b/endpoints/flight/index.js @@ -1,15 +1,10 @@ -var request = require('request'); -var $ = require('jquery'); -var h = require('../../lib/helpers.js'); +var request = require('request'), + $ = require('jquery'), + h = require('../../lib/helpers.js'), + app = require('../../server'); -exports.setup = function(server){ - server.post({path: '/flight', version: '1.0.0'}, slash); //Old - - server.get({path: '/flight', version: '1.0.0'}, slash); -} - -var slash = function(req, res, next){ - var data = req.params, +app.get('/flight', function(req, res){ + var data = req.query, url = ''; if(!data.type) data.type = ''; @@ -24,21 +19,20 @@ var slash = function(req, res, next){ }else if(data.type == 'arrivals' && data.language == 'en'){ url = 'http://www.kefairport.is/English/Timetables/Arrivals/'; }else{ - res.json(431,{'error':'Wrong parameters given!'}); - return next(); + return res.json(431,{'error':'Wrong parameters given!'}); } request.get({ headers: {'User-Agent': h.browser()}, url: url }, function(error, response, body){ - if(error || response.statusCode !== 200) { - throw new Error("www.kefairport.is refuses to respond or give back data"); - } + if(error || response.statusCode !== 200) + return res.json(500,{error:'www.kefairport.is refuses to respond or give back data'}); + try{ var data = $(body); }catch(error){ - throw new Error("Could not parse body");; + return res.json(500,{error:'Could not parse body'}); } var obj = { results: []}; @@ -66,7 +60,6 @@ var slash = function(req, res, next){ } }); - res.json(200,obj) - return next(); + return res.json(obj); }); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/endpoints/flight/tests/integration_test.js b/endpoints/flight/tests/integration_test.js index 6d9ff455..328b6ac7 100644 --- a/endpoints/flight/tests/integration_test.js +++ b/endpoints/flight/tests/integration_test.js @@ -10,6 +10,6 @@ describe('flight', function() { type: "departures" }); var resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor); - request.post(params, resultHandler); + request.get(params, resultHandler); }); }); diff --git a/endpoints/frontpage/index.js b/endpoints/frontpage/index.js index fa8025fe..c44b2cb7 100644 --- a/endpoints/frontpage/index.js +++ b/endpoints/frontpage/index.js @@ -1,31 +1,9 @@ -exports.setup = function(server){ - server.get({path: '/'}, getSlash); - server.post({path: '/'}, postSlash); -} +var app = require('../../server'); -var getSlash = function(req, res, next) { - // fs.readFile('public/index.html', 'utf8', function (err,data) { - // if (err) { - // h.logError(err,err.stack); - // res.json(200,{success:'failure',message:"Something went wrong"}); - // return next(); - // } - // res.charSet = 'utf8'; - // res.writeHead(200, { - // 'Content-Length': Buffer.byteLength(data), - // 'Content-Type': 'text/html;charset=utf8', - // }); - // res.write(data); - // res.end(); +app.get('/', function(req, res) { + return res.redirect(301,'http://docs.apis.is'); +}); - // return next(); - // }); - res.header('Location', 'http://docs.apis.is'); - res.send(302); - return next(false); -} - -var postSlash = function(req, res, next) { - res.json(200,{"info":"Velkominn á apis.is! Kíktu á docs.apis.is í vafranum þínum fyrir frekari upplýsingar!"}); - return next(); -} \ No newline at end of file +app.post('/', function(req, res) { + return res.json({"info":"Velkominn á apis.is! Kíktu á docs.apis.is í vafranum þínum fyrir frekari upplýsingar!"}); +}); \ No newline at end of file diff --git a/endpoints/lottery/index.js b/endpoints/lottery/index.js index cc52ce34..6f0ef5c6 100644 --- a/endpoints/lottery/index.js +++ b/endpoints/lottery/index.js @@ -1,40 +1,33 @@ -var request = require('request'); -var $ = require('jquery'); -var h = require('../../lib/helpers.js'); - -exports.setup = function(server) { - server.get({path: '/lottery', version: '1.0.0'}, getLotto); - server.get({path: '/lottery/lotto', version: '1.0.0'}, getLotto); - server.get({path: '/lottery/vikingslotto', version: '1.0.0'}, getViking); - server.get({path: '/lottery/eurojackpot', version: '1.0.0'}, getEurojackpot); -}; +var request = require('request'), + $ = require('jquery'), + app = require('../../server'); + -var getLotto = function (req, res, next) { +var getLotto = function (req, res) { getLottery(function(body) { - res.json(200, { + return res.json({ results: parseList(body) }); - return next(); }); }; -var getViking = function (req, res, next) { +app.get('/lottery', getLotto); +app.get('/lottery/lotto', getLotto); + +app.get('/lottery/vikingslotto', function(req, res) { getLottery(function(body) { - res.json(200, { + return res.json({ results: parseList(body) }); - return next(); }, 'https://games.lotto.is/lottoleikir/urslit/vikingalotto/'); -}; - -var getEurojackpot = function (req, res, next) { +}); +app.get('/lottery/eurojackpot', function(req, res) { getLottery(function(body) { - res.json(200, { + return res.json({ results: parseList(body) }); - return next(); }, 'https://games.lotto.is/lottoleikir/urslit/eurojackpot/'); -}; +}); var getLottery = function(callback, url) { url = url || 'https://igvefur.lotto.is/lottoleikir/urslit/lotto/'; diff --git a/endpoints/static_endpoints/frontpage.js b/endpoints/static_endpoints/frontpage.js index 304a3dff..11d39903 100644 --- a/endpoints/static_endpoints/frontpage.js +++ b/endpoints/static_endpoints/frontpage.js @@ -1,18 +1,9 @@ -exports.setup = function(server){ - server.get({path: '/'}, getFrontpage); - server.post({path: '/'}, postFrontpage); -} +var app = require('../../server'); -var getFrontpage = function(req, res, next) { - res.header('Location', 'http://docs.apis.is'); - res.send(302); - return next(false); -} - -var postFrontpage = function(req, res, next) { - res.header("Access-Control-Allow-Origin", "*"); - res.header("Access-Control-Allow-Headers", "X-Requested-With"); - +app.get('/', function(req,res){ + return res.redirect(301,'http://docs.apis.is') +}); +app.post('/', function(req, res, next) { var obj = { "info": { "english": "Hey there! Check out docs.apis.is in your browser for mor info", @@ -20,6 +11,5 @@ var postFrontpage = function(req, res, next) { } }; - res.json(200,obj); - return next(); -} \ No newline at end of file + return res.json(obj); +}); \ No newline at end of file diff --git a/endpoints/tv/index.js b/endpoints/tv/index.js index 0fbedc25..3bd440b5 100644 --- a/endpoints/tv/index.js +++ b/endpoints/tv/index.js @@ -1,7 +1,8 @@ -var request = require('request'); -var moment = require('moment'); -var parseString = require('xml2js').parseString; -var h = require('../../lib/helpers.js'); +var request = require('request'), + moment = require('moment'), + parseString = require('xml2js').parseString, + h = require('../../lib/helpers.js'), + app = require('../../server'); var schedStruct = { title: '', @@ -20,21 +21,34 @@ var schedStruct = { actors: '' }; -exports.setup = function (server) { - server.get({path: '/tv', version: '1.0.0'}, getTV); - server.get({path: '/tv/ruv', version: '1.0.0'}, getRuv); - server.get({path: '/tv/stod2', version: '1.0.0'}, getStod2); -}; - +app.get('/tv', function (req, res) { + return getRuv(req, res); +}); +app.get('/tv/ruv', function (req, res) { + var url = 'http://muninn.ruv.is/files/xml/ruv/'; -var getTV = function (req, res, next) { - // This redirects to the default for time being. - getRuv(req, res, next); - return next(); -}; + if (req.params.date) { + if (moment(req.params.date).isValid()) { + var date = moment(req.params.date); + // Example : http://muninn.ruv.is/files/xml/ruv/2013-06-11/ + url += date.format('YYYY-MM-DD'); + } + } + request.get({ + headers: {'User-Agent': h.browser()}, + url: url + }, function (error, response, body) { + if (error) throw new Error(url + ' did not respond'); -var getStod2 = function (req, res, next) { + parseRuv(function (data) { + res.json(200, { + results: data + }) + }, body); + }); +}); +app.get('/tv/stod2', function (req, res) { var url = 'http://stod2.is/XML--dagskrar-feed/XML-Stod-2-dagurinn'; request.get({ @@ -49,7 +63,7 @@ var getStod2 = function (req, res, next) { }) }, body); }) -}; +}); var parseStod2 = function (callback, data) { parseString(data, function (err, result, title) { @@ -75,41 +89,10 @@ var parseStod2 = function (callback, data) { } }) } - return callback(schedule); - - }); -}; - -var getRuv = function (req, res, next) { - var url = 'http://muninn.ruv.is/files/xml/ruv/'; - - if (req.params.date) { - if (moment(req.params.date).isValid()) { - var date = moment(req.params.date); - // Example : http://muninn.ruv.is/files/xml/ruv/2013-06-11/ - url += date.format('YYYY-MM-DD'); - } - } - - request.get({ - headers: {'User-Agent': h.browser()}, - url: url - }, function (error, response, body) { - if (error) throw new Error(url + ' did not respond'); - - parseRuv(function (data) { - res.json(200, { - results: data - }) - }, body); - - return next(); - }); }; - var parseRuv = function (callback, data) { parseString(data, function (err, result, title) { diff --git a/lib/test_helpers.js b/lib/test_helpers.js index 71fc850d..667aad26 100644 --- a/lib/test_helpers.js +++ b/lib/test_helpers.js @@ -36,7 +36,12 @@ function assertTypesOfFields(fields, arr) { exports.testRequestHandlerForFields = function(done, fieldsToCheckFor, customCallback) { return function(err, res, body) { if (err) throw err; - var json = JSON.parse(body); + var json; + try{ + json = JSON.parse(body); + }catch(e){ + throw e; + } // Check for the presence of the results property assertResults(json); @@ -63,7 +68,7 @@ exports.testRequestParams = function(path, form) { return { url: "http://" + config.host + ":" + config.port + path, method: "GET", - form: form, + qs: form, headers: [ "Content-type: application/json" ] }; }; diff --git a/package.json b/package.json index c529a72b..37590f1c 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,6 @@ } ], "dependencies": { - "restify": "2.4.x", "request": "2.11.x", "jquery": "1.8.x", "scraper": "0.0.9", @@ -30,8 +29,8 @@ "mocha": "~1.8.2", "cheerio": "0.10.x", "isn2wgs": "0.0.1", - "xtend": "2.x", - "underscore": "~1.5.1" + "underscore": "~1.5.1", + "express": "~3.3.8" }, "scripts": { "test": "node_modules/mocha/bin/mocha test/integration" diff --git a/server.js b/server.js index c2a61a46..e5de8325 100644 --- a/server.js +++ b/server.js @@ -1,9 +1,11 @@ var express = require('express'), - app = module.exports = express(), + app = module.exports = express(), config = require('./config'), fileModule = require('file'); +//Get the posted params with req.body.KEY app.use(express.bodyParser()); + app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); @@ -15,17 +17,10 @@ app.use(function(req, res, next) { return res.send(200); }); -// app.on('uncaughtException', function (req, res, route, err) { -// console.log("======== Uncaught exception ========="); -// console.log("In: ", req.url, req.method); -// if (Object.keys(req.params).length > 0) { -// console.log("Params: ", util.inspect(req.params).replace(/\n/g,'')); -// } -// console.log("Headers: ", util.inspect(req.headers).replace(/\n/g,'')); -// console.log(err.stack); -// res.send(new restify.InternalError(err, 'Internal error in endpoint, please let us know.')); -// return (true); -// }); +app.use(function(err, req, res, next){ + console.error(err); + res.send('Fail Whale, yo.'); +}); //Load all endpoints in the endpoints folder fileModule.walkSync('./endpoints', function(dirPath, dirs, files){ @@ -36,11 +31,5 @@ fileModule.walkSync('./endpoints', function(dirPath, dirs, files){ } }); - -app.get('/',function(req,res){ - res.json({}) -}) - - app.listen(config.port); console.log('Server running at port: ' + config.port); \ No newline at end of file