-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
53 lines (45 loc) · 1.69 KB
/
server.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
// Import the installed modules.
const express = require('express');
const responseTime = require('response-time')
const axios = require('axios');
const redis = require('redis');
const app = express();
// create and connect redis client to local instance.
const client = redis.createClient();
// Print redis errors to the console
client.on('error', (err) => {
console.log("Error " + err);
});
// use response-time as a middleware
app.use(responseTime());
// create an api/search route
app.get('/api/search', (req, res) => {
// Extract the query from url and trim trailing spaces
const query = (req.query.query).trim();
// Build the Wikipedia API url
const searchUrl = `https://en.wikipedia.org/w/api.php?action=parse&format=json§ion=0&page=${query}`;
// Try fetching the result from Redis first in case we have it cached
return client.get(`wikipedia:${query}`, (err, result) => {
// If that key exist in Redis store
if (result) {
const resultJSON = JSON.parse(result);
return res.status(200).json(resultJSON);
} else { // Key does not exist in Redis store
// Fetch directly from Wikipedia API
return axios.get(searchUrl)
.then(response => {
const responseJSON = response.data;
// Save the Wikipedia API response in Redis store
client.setex(`wikipedia:${query}`, 3600, JSON.stringify({ source: 'Redis Cache', ...responseJSON, }));
// Send JSON response to client
return res.status(200).json({ source: 'Wikipedia API', ...responseJSON, });
})
.catch(err => {
return res.json(err);
});
}
});
});
app.listen(3000, () => {
console.log('Server listening on port: ', 3000);
});