This repository has been archived by the owner on Apr 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
hapi.js
71 lines (52 loc) · 1.52 KB
/
hapi.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
65
66
67
68
69
70
71
'use strict';
// After starting this example load http://localhost:8080
// hit refresh, you will notice that it loads the response
// from cache for the first 5 seconds and then reloads the cache
// Load modules
const CatboxMongo = require('..');
const Hapi = require('hapi');
// create server instance with MongoDB cache
const server = new Hapi.Server({
port: 8080,
cache: [
{
name: 'mongoCache',
engine: CatboxMongo,
host: '127.0.0.1',
partition: 'example-cache'
}
]
});
// define a cache segment to store cache items
const Cache = server.cache({ segment: 'examples', expiresIn: 1000 * 5 });
// wildcard route that responds all requests
// either with data from cache or default string
server.route({
method: 'GET',
path: '/{path*}',
handler: async (request, h) => {
const key = {
segment: 'examples',
id: 'myExample'
};
// get item from cache segment
const cached = await Cache.get(key);
if (cached) {
return `From cache: ${cached.item}`;
}
// fill cache with item
await Cache.set(key, { item: 'my example' }, 5000);
return 'my example';
}
});
const start = async function () {
try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}
console.log('Server running at:', server.info.uri);
};
start();