From 46fc4e9bf2d65a66c5ca19e3cf7225cb18533a4c Mon Sep 17 00:00:00 2001 From: MynahMarie Date: Thu, 30 Nov 2017 11:55:21 +0200 Subject: [PATCH] Modularize the handler.js file and clean up with Linter Relates #54 and #66 --- public/main.js | 108 ++++++++++++++++----------------- src/handler.js | 102 ------------------------------- src/handlers/handleError.js | 7 +++ src/handlers/handleHome.js | 17 ++++++ src/handlers/handleRequests.js | 54 +++++++++++++++++ src/handlers/handleStatic.js | 25 ++++++++ src/model.js | 0 src/router.js | 17 +++--- src/server.js | 6 +- tests/back-endTesting.js | 57 +++++++++++------ 10 files changed, 205 insertions(+), 188 deletions(-) delete mode 100644 src/handler.js create mode 100644 src/handlers/handleError.js create mode 100644 src/handlers/handleHome.js create mode 100644 src/handlers/handleRequests.js create mode 100644 src/handlers/handleStatic.js delete mode 100644 src/model.js diff --git a/public/main.js b/public/main.js index 78aa902..4060cca 100644 --- a/public/main.js +++ b/public/main.js @@ -13,7 +13,7 @@ function keepRunning() { } } -//handles the xhr request +// Handles the xhr request function fetch(url, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { @@ -23,21 +23,21 @@ function fetch(url, callback) { console.log(xhr.readyState, xhr.status); } }; - xhr.open("GET", url); + xhr.open('GET', url); xhr.send(); } -//function that handles the data recieved from the server +// Function that handles the data recieved from the server function filterData() { - var place = document.getElementById("cities").value; - searchPath = "/submit?search=" + place; + var place = document.getElementById('cities').value; + searchPath = '/submit?search=' + place; fetch(searchPath, function(error, response) { if (error) { - console.log("error with getting data from the server : ", error); + console.log('error with getting data from the server : ', error); } else { var clock = JSON.parse(response.clock); - var timeL = clock.formatted.split(" ")[1].split(":"); + var timeL = clock.formatted.split(' ')[1].split(':'); watch.hours = parseInt(timeL[0]); watch.minutes = parseInt(timeL[1]); watch.seconds = parseInt(timeL[2]); @@ -46,39 +46,39 @@ function filterData() { }); } -//rendering the data +// Rendering the data function renderInfos(response) { var time_infos = JSON.parse(response.clock); var weather_infos = JSON.parse(response.weather); - document.getElementById("weather").style.backgroundColor = "#66d3ff"; - document.getElementById("other").style.backgroundColor = "#d2d7dd"; + document.getElementById('weather').style.backgroundColor = '#66d3ff'; + document.getElementById('other').style.backgroundColor = '#d2d7dd'; - document.getElementById("weather_infos").innerHTML = ""; - document.getElementById("other_infos").innerHTML = ""; - document.getElementById("weather_icon").setAttribute("src", ""); + document.getElementById('weather_infos').innerHTML = ''; + document.getElementById('other_infos').innerHTML = ''; + document.getElementById('weather_icon').setAttribute('src', ''); - var list_other = document.getElementById("other_infos"); + var list_other = document.getElementById('other_infos'); var timestamp = time_infos.formatted; - var display_time = document.createElement("li"); - display_time.textContent = "Date and Time: " + timestamp; + var display_time = document.createElement('li'); + display_time.textContent = 'Date and Time: ' + timestamp; list_other.appendChild(display_time); var city = time_infos.zoneName; - var display_city = document.createElement("li"); - display_city.textContent = "Zone: " + city; + var display_city = document.createElement('li'); + display_city.textContent = 'Zone: ' + city; list_other.appendChild(display_city); var country = time_infos.countryName; - var display_country = document.createElement("li"); - display_country.textContent = "Country: " + country; + var display_country = document.createElement('li'); + display_country.textContent = 'Country: ' + country; list_other.appendChild(display_country); var latitude = weather_infos.coord.lat; var longitude = weather_infos.coord.lon; - var coords = document.createElement("li"); - coords.textContent = "Coordinates: " + latitude + ", " + longitude; + var coords = document.createElement('li'); + coords.textContent = 'Coordinates: ' + latitude + ', ' + longitude; list_other.appendChild(coords); //------Weather Infos---------// @@ -89,50 +89,50 @@ function renderInfos(response) { var wind_speed = weather_infos.wind.speed; var weather_icon = weather_infos.weather[0].icon; - var list_weather = document.getElementById("weather_infos"); + var list_weather = document.getElementById('weather_infos'); - var temp_display = document.createElement("li"); - temp_display.textContent = "Current Temperature: " + temp_F + "°F"; + var temp_display = document.createElement('li'); + temp_display.textContent = 'Current Temperature: ' + temp_F + '°F'; list_weather.appendChild(temp_display); - var weather_descript = document.createElement("li"); - weather_descript.textContent = "Description: " + weather_main; + var weather_descript = document.createElement('li'); + weather_descript.textContent = 'Description: ' + weather_main; list_weather.appendChild(weather_descript); - var display_humid = document.createElement("li"); - display_humid.textContent = "Humidity: " + humidity + "%"; + var display_humid = document.createElement('li'); + display_humid.textContent = 'Humidity: ' + humidity + '%'; list_weather.appendChild(display_humid); - var display_wind = document.createElement("li"); - display_wind.textContent = "Wind Speed: " + wind_speed; + var display_wind = document.createElement('li'); + display_wind.textContent = 'Wind Speed: ' + wind_speed; list_weather.appendChild(display_wind); - document.getElementById("weather_icon").src = - "https://openweathermap.org/img/w/" + weather_icon + ".png"; + document.getElementById('weather_icon').src = + 'https://openweathermap.org/img/w/' + weather_icon + '.png'; } function drawFace(ctx, radius) { var grad; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); - ctx.fillStyle = "white"; + ctx.fillStyle = 'white'; ctx.fill(); grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05); - grad.addColorStop(0, "#333"); - grad.addColorStop(0.5, "white"); - grad.addColorStop(1, "#333"); + grad.addColorStop(0, '#333'); + grad.addColorStop(0.5, 'white'); + grad.addColorStop(1, '#333'); ctx.strokeStyle = grad; ctx.lineWidth = radius * 0.1; ctx.stroke(); ctx.beginPath(); ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI); - ctx.fillStyle = "#333"; + ctx.fillStyle = '#333'; ctx.fill(); } function drawNumbers(ctx, radius) { var ang; var num; - ctx.font = radius * 0.15 + "px arial"; - ctx.textBaseline = "middle"; - ctx.textAlign = "center"; + ctx.font = radius * 0.15 + 'px arial'; + ctx.textBaseline = 'middle'; + ctx.textAlign = 'center'; for (num = 1; num < 13; num++) { ang = num * Math.PI / 6; ctx.rotate(ang); @@ -155,16 +155,16 @@ function drawTime(ctx, radius) { if (hour > 18 || hour < 6) { document.body.style.backgroundImage = "url('https://scromy.com/wp-content/uploads/2017/01/night-sky-wallpapers-phone.jpg')"; - document.querySelector(".content__header__title").style.color = "white"; - document.querySelector(".content__header__tagline").style.color = "white"; + document.querySelector('.content__header__title').style.color = 'white'; + document.querySelector('.content__header__tagline').style.color = 'white'; } else { document.body.style.backgroundImage = "url('https://www.mycadsite.com/tutorials/level_3/images/sky.jpg')"; - document.querySelector(".content__header__title").style.color = "#000000"; - document.querySelector(".content__header__tagline").style.color = "#000000"; + document.querySelector('.content__header__title').style.color = '#000000'; + document.querySelector('.content__header__tagline').style.color = '#000000'; } - //hour + // Hour hour = hour % 12; hour = hour * Math.PI / 6 + @@ -172,10 +172,10 @@ function drawTime(ctx, radius) { second * Math.PI / (360 * 60); drawHand(ctx, hour, radius * 0.5, radius * 0.07); - //minute + // Minute minute = minute * Math.PI / 30 + second * Math.PI / (30 * 60); drawHand(ctx, minute, radius * 0.8, radius * 0.07); - // second + // Second second = second * Math.PI / 30; drawHand(ctx, second, radius * 0.9, radius * 0.02); } @@ -183,7 +183,7 @@ function drawTime(ctx, radius) { function drawHand(ctx, pos, length, width) { ctx.beginPath(); ctx.lineWidth = width; - ctx.lineCap = "round"; + ctx.lineCap = 'round'; ctx.moveTo(0, 0); ctx.rotate(pos); ctx.lineTo(0, -length); @@ -202,17 +202,17 @@ var now = new Date(); const watch = { hours: now.getHours(), minutes: now.getMinutes(), - seconds: now.getSeconds() + seconds: now.getSeconds(), }; -//submitButton`s event listener -document.getElementById("submitButton").addEventListener("click", function() { +// submitButton's event listener +document.getElementById('submitButton').addEventListener('click', function() { event.preventDefault(); filterData(); }); -var canvas = document.getElementById("canvas"); -var ctx = canvas.getContext("2d"); +var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); var radius = canvas.height / 2; ctx.translate(radius, radius); radius = radius * 0.9; diff --git a/src/handler.js b/src/handler.js deleted file mode 100644 index 0301f76..0000000 --- a/src/handler.js +++ /dev/null @@ -1,102 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const req = require('request'); - -// object that holds the data recieved -const dataObj = { - clock: '', - weather: '', -}; - -// filters the data recieved by both apis -function filterData(body, num) { - // const parsedBody = JSON.parse(body); - - if (num === 0) { - dataObj.clock = body; - } - if (num === 1) { - dataObj.weather = body; - } -} - -// handles the Errors -function handleError(error, request, response) { - response.writeHead(404, { 'Content-Type': 'text/html' }); - response.end('

404 PAGE NOT FOUND

'); -} - -// handles the home route - / -function handleHome(request, response) { - const filePath = path.join(__dirname, '..', 'public', 'index.html'); - // handler.staticFiles (request, response, file); - fs.readFile(filePath, (error, file) => { - if (error) { - handleError(error, request, response); - } else { - response.writeHead(200, { 'Context-Type': 'text/html' }); - response.end(file); - } - }); -} - -// handles the rest of the public files -function handleStatic(request, response) { - const filePath = path.join(__dirname, '..', 'public', request.url); - const extension = request.url.split('.')[1]; - const extensionType = { - html: 'text/html', - css: 'text/css', - js: 'application/javascript', - }[extension]; - - fs.readFile(filePath, (error, file) => { - if (error) { - handleError(error, request, response); - } else { - response.writeHead(200, { 'Context-Type': extensionType }); - response.end(file); - } - }); -} - -// send an API request to other server -function handleRequest(request, response) { - const query = request.url.split('=')[1]; - const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${ - query - }&appid=82e45ca76afa605e31bf2540d2afe634`; - - req(weatherUrl, (error, res, body) => { - if (error) { - handleError(error, request, response); - } else { - filterData(body, 1); - - // sending the second api - const parsedBody = JSON.parse(body); - const { coord: { lon, lat } } = parsedBody; - // const long = parsedBody.coord.lon; - const timeUrl = `http://api.timezonedb.com/v2/get-time-zone?key=UOEG6CXIM1AQ&format=json&by=position&lat=${ - lat - }&lng=${lon}`; - - req(timeUrl, (err, result, timeBody) => { - if (err) { - handleError(err, request, response); - } else { - filterData(timeBody, 0); - response.writeHead(200, { 'Content-Type': 'application/json' }); - response.end(JSON.stringify(dataObj)); - } - }); - } - }); -} - -module.exports = { - handleHome, - handleStatic, - handleRequest, - handleError, -}; diff --git a/src/handlers/handleError.js b/src/handlers/handleError.js new file mode 100644 index 0000000..cb618fc --- /dev/null +++ b/src/handlers/handleError.js @@ -0,0 +1,7 @@ +// handles the Errors +const handleError = (error, request, response) => { + response.writeHead(404, { 'Content-Type': 'text/html' }); + response.end('

404 PAGE NOT FOUND

'); +}; + +module.exports = handleError; diff --git a/src/handlers/handleHome.js b/src/handlers/handleHome.js new file mode 100644 index 0000000..842ae59 --- /dev/null +++ b/src/handlers/handleHome.js @@ -0,0 +1,17 @@ +const fs = require('fs'); +const path = require('path'); +const handleError = require('./handleError'); + +const handleHome = (request, response) => { + const filePath = path.join(__dirname, '..', '..', 'public', 'index.html'); + fs.readFile(filePath, (error, file) => { + if (error) { + handleError(error, request, response); + } else { + response.writeHead(200, { 'Context-Type': 'text/html' }); + response.end(file); + } + }); +}; + +module.exports = handleHome; diff --git a/src/handlers/handleRequests.js b/src/handlers/handleRequests.js new file mode 100644 index 0000000..206d7db --- /dev/null +++ b/src/handlers/handleRequests.js @@ -0,0 +1,54 @@ +const req = require('request'); +const handleError = require('./handleError'); + +// object that holds the data recieved +const dataObj = { + clock: '', + weather: '', +}; + +// filters the data recieved by both apis +function filterData(body, num) { + if (num === 0) { + dataObj.clock = body; + } + if (num === 1) { + dataObj.weather = body; + } +} + +// send an API request to other server +const handleRequest = (request, response) => { + const query = request.url.split('=')[1]; + const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${ + query + }&appid=82e45ca76afa605e31bf2540d2afe634`; + + req(weatherUrl, (error, res, body) => { + if (error) { + handleError(error, request, response); + } else { + filterData(body, 1); + + // sending the second api + const parsedBody = JSON.parse(body); + const { coord: { lon, lat } } = parsedBody; + // const long = parsedBody.coord.lon; + const timeUrl = `http://api.timezonedb.com/v2/get-time-zone?key=UOEG6CXIM1AQ&format=json&by=position&lat=${ + lat + }&lng=${lon}`; + + req(timeUrl, (err, result, timeBody) => { + if (err) { + handleError(err, request, response); + } else { + filterData(timeBody, 0); + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify(dataObj)); + } + }); + } + }); +}; + +module.exports = handleRequest; diff --git a/src/handlers/handleStatic.js b/src/handlers/handleStatic.js new file mode 100644 index 0000000..af68c84 --- /dev/null +++ b/src/handlers/handleStatic.js @@ -0,0 +1,25 @@ +const fs = require('fs'); +const path = require('path'); +const handleError = require('./handleError'); + +// handles the rest of the public files +const handleStatic = (request, response) => { + const filePath = path.join(__dirname, '..', '..', 'public', request.url); + const extension = request.url.split('.')[1]; + const extensionType = { + html: 'text/html', + css: 'text/css', + js: 'application/javascript', + }[extension]; + + fs.readFile(filePath, (error, file) => { + if (error) { + handleError(error, request, response); + } else { + response.writeHead(200, { 'Context-Type': extensionType }); + response.end(file); + } + }); +}; + +module.exports = handleStatic; diff --git a/src/model.js b/src/model.js deleted file mode 100644 index e69de29..0000000 diff --git a/src/router.js b/src/router.js index 0cc42eb..1a02d54 100644 --- a/src/router.js +++ b/src/router.js @@ -1,19 +1,16 @@ -const {handleHome, handleStatic,handleRequest, handleError} = require("./handler.js"); +const handleHome = require('./handlers/handleHome'); +const handleStatic = require('./handlers/handleStatic'); +const handleRequest = require('./handlers/handleRequests'); -function router (request, response) { +const router = (request, response) => { let baseUrl = request.url; - if (baseUrl === "/") { - // console.log(baseUrl); + if (baseUrl === '/') { handleHome(request, response); - } else if (baseUrl.split('?')[0] === '/submit') { - // console.log(baseUrl); - handleRequest(request,response); - + handleRequest(request, response); } else { - // console.log(baseUrl); handleStatic(request, response); } -} +}; module.exports = router; diff --git a/src/server.js b/src/server.js index 50dc1fe..8711993 100644 --- a/src/server.js +++ b/src/server.js @@ -1,9 +1,9 @@ -const http = require("http"); -const router = require("./router"); +const http = require('http'); +const router = require('./router'); const host = process.env.HOST || 'localhost'; const port = process.env.PORT || 3000; http.createServer(router).listen(port, () => { console.log(`Server running at port ${port}`); -}) +}); diff --git a/tests/back-endTesting.js b/tests/back-endTesting.js index 526d143..f9be14d 100644 --- a/tests/back-endTesting.js +++ b/tests/back-endTesting.js @@ -2,34 +2,53 @@ const test = require('tape'); const shot = require('shot'); const router = require('../src/router.js'); -//TESTING THE ROUTER +// TESTING THE ROUTER // Home Route test('Home route returns a status code of 200', (t) => { shot.inject(router, { method: 'get', url: '/' }, (res) => { t.equal(res.statusCode, 200, 'should respond with status code of 200'); - t.notEqual(res.payload,undefined, 'response should contain an html file'); + t.notEqual(res.payload, undefined, 'response should contain an html file'); t.end(); - }) -}) -//static files + }); +}); + +// static files test('Testing the router for the static files', (t) => { shot.inject(router, { method: 'get', url: '/style.css' }, (res) => { - t.equal(res.statusCode, 200, 'should respond with status code of 200 for the css file'); - t.notEqual(res.payload,undefined, 'response should contain a css file'); - - }) + t.equal( + res.statusCode, + 200, + 'should respond with status code of 200 for the css file', + ); + t.notEqual(res.payload, undefined, 'response should contain a css file'); + }); shot.inject(router, { method: 'get', url: '/main.js' }, (res) => { - t.equal(res.statusCode, 200, 'should respond with status code of 200 for the JS file'); - t.notEqual(res.payload,undefined, 'response should contain a JS file'); - - }) + t.equal( + res.statusCode, + 200, + 'should respond with status code of 200 for the JS file', + ); + t.notEqual(res.payload, undefined, 'response should contain a JS file'); + }); t.end(); -}) +}); test('Testing the router for the time api', (t) => { - shot.inject(router, { method: 'get', url: "/submit?search=Amsterdam" }, (res) => { - t.equal(res.statusCode, 200, 'should respond with status code of 200 for the JSON data'); - t.notEqual(res.payload,undefined, 'response should contain a JSON object'); - }) + shot.inject( + router, + { method: 'get', url: '/submit?search=Amsterdam' }, + (res) => { + t.equal( + res.statusCode, + 200, + 'should respond with status code of 200 for the JSON data', + ); + t.notEqual( + res.payload, + undefined, + 'response should contain a JSON object', + ); + }, + ); t.end(); -}) +});