File: /mnt/data/smarthr-co-in/demo/mobile/buyer/pwa/template-rtl/server.js
'use strict';
const express = require('express');
const fetch = require('node-fetch');
const redirectToHTTPS = require('express-http-to-https').redirectToHTTPS;
// Change this to add a delay (ms) before the server responds.
const FORECAST_DELAY = 0;
// If running locally, set your Dark Sky API key here
const API_KEY = process.env.DARKSKY_API_KEY;
const BASE_URL = `https://api.darksky.net/forecast`;
/**
* Generates a fake forecast in case the weather API is not available.
*
* @param {String} location GPS location to use.
* @return {Object} forecast object.
*/
function generateFakeForecast(location) {
location = location || '40.7720232,-73.9732319';
const commaAt = location.indexOf(',');
// Create a new copy of the forecast
const result = Object.assign({}, fakeForecast);
result.latitude = parseFloat(location.substr(0, commaAt));
result.longitude = parseFloat(location.substr(commaAt + 1));
return result;
}
/**
* Gets the weather forecast from the Dark Sky API for the given location.
*
* @param {Request} req request object from Express.
* @param {Response} resp response object from Express.
*/
function getForecast(req, resp) {
const location = req.params.location || '40.7720232,-73.9732319';
const url = `${BASE_URL}/${API_KEY}/${location}`;
fetch(url).then((resp) => {
if (resp.status !== 200) {
throw new Error(resp.statusText);
}
return resp.json();
}).then((data) => {
setTimeout(() => {
resp.json(data);
}, FORECAST_DELAY);
}).catch((err) => {
console.error('Dark Sky API Error:', err.message);
resp.json(generateFakeForecast(location));
});
}
/**
* Starts the Express server.
*
* @return {ExpressServer} instance of the Express server.
*/
function startServer() {
const app = express();
// Redirect HTTP to HTTPS,
app.use(redirectToHTTPS([/localhost:(\d{4})/], [], 301));
// Logging for each request
app.use((req, resp, next) => {
const now = new Date();
const time = `${now.toLocaleDateString()} - ${now.toLocaleTimeString()}`;
const path = `"${req.method} ${req.path}"`;
const m = `${req.ip} - ${time} - ${path}`;
// eslint-disable-next-line no-console
console.log(m);
next();
});
// Handle requests for static files
app.use(express.static('public'));
// Start the server
return app.listen('8000', () => {
// eslint-disable-next-line no-console
console.log('Local DevServer Started on port 8000...');
});
}
startServer();