上一个实验 中,我们Route的一些特性,本次实验我们将进一步聚焦在 Route 的 Pre 属性上。

添加 boom 依赖

在命令行执行:

1
npm install boom

演示代码

在项目中新建名为: RoutePre.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const Hapi = require('hapi');
const Boom = require('boom');

const server = new Hapi.Server({
host: 'localhost',
port: 8000
});

const userDB = {
john: { id: 1, meta: 'test' }
};

const connectionDB = {
john: ['tim', 'bob']
};


const setupDBConnections = function (request, h) {

request.userDB = userDB;
request.connectionDB = connectionDB;

return h.continue;
};

const checkUserExists = function (request, h) {

console.log('[checkUserExists], name = %s', request.params.name);

if (!request.userDB[request.params.name]) {
return Boom.notFound();
}

return h.continue;
};

const getUserDetails = function (request, h) {

return h.request.userDB[request.params.name];
};

const getUserConnections = function (request, h) {

return h.request.connectionDB[request.params.name];
};


server.route({
method: 'GET',
path: '/hello/{name}',
config: {
description: 'Return an object with a message of hello to the name provided',
pre: [
{ method: setupDBConnections },
{ method: checkUserExists }, // series
[
{ method: getUserDetails, assign: 'userDetails' }, // parallel
{ method: getUserConnections, assign: 'userConnections' } // parallel
]
],
handler: function (request, h) {

const user = request.pre.userDetails;
user.connections = request.pre.userConnections;

const time = (new Date().getTime() - request.info.received) / 1000;
console.log(`Request time taken: #123;time}`);

return user;
}
}
});


const start = async function() {

try {
await server.start();

console.log('Server running at:', server.info.uri);

} catch(err) {
console.log(err);
process.exit(1);
}
}

start();