-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (54 loc) · 1.55 KB
/
index.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
59
60
61
62
63
64
const Koa = require('koa');
const app = new Koa();
const os = require('os');
let redis = require("redis");
// You can also use node_redis with promises: https://github.com/NodeRedis/node_redis#promises
let bluebird = require('bluebird');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
let redisClient = redis.createClient({
host: process.env.NODE_ENV === 'dev'
? '' // use default: 127.0.0.1
: 'redis' // link to container: redis
});
let redisAvailable = false;
const PORT = 3000;
let visits = 0;
redisClient.on("error", (err) => {
redisAvailable = false;
console.log("Redis Error " + err);
});
redisClient.on('ready', () => {
redisAvailable = true;
console.log("Redis is ready");
});
const getCache = async (key) => {
if(!redisAvailable){
return 'Redis is not available!';
}
let data = await redisClient.getAsync(key);
if(data) {
data = JSON.parse(data.toString());
}
return data;
};
app.use(async ctx => {
console.log('A Request!');
let hostname = os.hostname();
try {
if(redisAvailable) {
redisClient.incr('visits');
}
visits = await getCache('visits');
}
catch(e) {
visits = 'Redis Error!';
console.log('redisClient.incr() Error: ', e);
}
ctx.type = 'html';
ctx.body = `<h3>Bonjour Monde! </h3>
<p>Hostname: <b style="color: red;">${hostname}</b></p>
<p>Site visits from Redis: <b style="color: red;">${visits}</b></p>`;
});
console.log('APP START!!! App is running on port: ', PORT);
app.listen(PORT);