-
Notifications
You must be signed in to change notification settings - Fork 2
/
caching_example.js
58 lines (47 loc) · 1.64 KB
/
caching_example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import constants from './constants.js'
import { createClient } from 'redis'
import axios from 'axios'
const client = createClient();
await client.connect();
const keyCheck = () => {
if (!process.env.WEATHER_API_KEY) {
console.error(`No Weather API key detected as an ENVIRONMENT VARIABLE.
Head to https://openweathermap.org/appid to get a free API key.
Then store the key in an environment variable from the command line:
$ export WEATHER_API_KEY=<your api key>`)
quit()
}
}
const quit = () => {
client.quit()
process.exit()
}
const cityEndpoint = (city) => `${constants.endpoint(city)}${constants.key}`
/* Returns a JSON object of the current weather conditions for a given city */
const getWeather = async (city) => {
/* Check if WEATHER_API_KEY exists in Environment Variables */
keyCheck()
/* Check Redis for cached entry first */
let cacheEntry = await client.get(`weather:${city}`)
/* If Redis returns a cache hit, */
if (cacheEntry) {
cacheEntry = JSON.parse(cacheEntry)
/* return the entry */
return {...cacheEntry, 'source' : 'cache'}
}
/* If Redis returns a cache miss, fetch and return data from the API */
const apiResponse = await axios.get(cityEndpoint(city))
/* Add the entry to Redis for next time and set an expiry of one hour */
client.set(
`weather:${city}`, JSON.stringify(apiResponse.data),
{EX : 60 * 60})
/* Return the database entry */
return {...apiResponse.data, 'source' : 'API' }
}
const city = 'Oakland'
const t0 = new Date().getTime()
const weather = await getWeather(city)
const t1 = new Date().getTime()
weather.responseTime = `${t1-t0}ms`
console.log(weather)
quit()