Caching Server for waeather

This commit is contained in:
nicco 2017-12-27 19:21:45 +01:00
parent 951e5d8276
commit a99aaff117
5 changed files with 5005 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
# Ignore Node Deps
node_modules

90
cache/cache.js vendored Normal file
View File

@ -0,0 +1,90 @@
const http = require('http')
const https = require('https')
// GET YOUR OWN AT: https://openweathermap.org/appid
const APP_KEY = 'myAppId'
const REGEXP = {
URL: /^\/[\d]{1,8}$/
}
const API = {
// Define max 60 calls per 1 Minute
MAX_CALLS: 60,
INTERVAL: 1000 * 60, // 1 Minute
current_calls: 0,
last_reset: Date.now(),
}
const CACHE = {}
const MAX_AGE = 60 * 1000 // 1 Minute
const LAST_UPDATE_KEY = 'last_update'
function getForZip(zip) {
return new Promise((resolve, reject) => {
// If interval is over, reset max count
if (Date.now() - API.last_reset > API.INTERVAL) {
API.last_reset = Date.now()
API.current_calls = 0
}
// Check if too many calls were already made
if (API.current_calls > API.MAX_CALLS)
resolve()
API.current_calls++;
// Make the call
https.get({
host: 'api.openweathermap.org',
path: `/data/2.5/forecast?APPID=${APP_KEY}&zip=${zip},DE&units=metric`,
timeout: 15 * 1000,
}, res => {
res.setEncoding('utf8')
let body = ''
res.on('data', data => {
body += data
})
res.on('end', () => {
const data = JSON.parse(body)
data[LAST_UPDATE_KEY] = Date.now()
resolve(data)
})
})
})
}
function getUrlFromPath(path) {
// Check if url is valid
if (!REGEXP.URL.test(path))
return false
else
// Exctract ZIP code
return path.replace('/', '')
}
const server = http.createServer(async(req, res) => {
const zip = getUrlFromPath(req.url)
// Check if url is valid
if (zip === false) {
res.writeHead(400, {})
res.end()
return
}
// If there is no cached version, get it
// If the last cached version is older than MAX_AGE, get it
if (CACHE[zip] === undefined || Date.now() - CACHE[zip][LAST_UPDATE_KEY] > MAX_AGE)
CACHE[zip] = await getForZip(zip)
res.writeHead(200, {
'Content-Type': 'application/json',
})
res.write(JSON.stringify(CACHE[zip] || {}))
res.end()
})
server.listen(8000)

4895
cache/package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

18
cache/package.json vendored Normal file
View File

@ -0,0 +1,18 @@
{
"name": "dvb",
"version": "1.0.0",
"description": "DVB Monitor App",
"dependencies": {},
"devDependencies": {
"css-loader": "latest",
"forever": "latest",
"style-loader": "latest",
"webpack": "latest"
},
"repository": {
"type": "git",
"url": "https://github.com/CupCakeArmy/dvb"
},
"author": "",
"license": "MIT"
}