-
Notifications
You must be signed in to change notification settings - Fork 7
/
hapi-plugin.js
69 lines (59 loc) · 1.91 KB
/
hapi-plugin.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
/* eslint-disable no-underscore-dangle */
'use strict';
const utils = require('@podium/utils');
const pkg = require('../../package.json');
// Hapi v17 or newer
const PodiumPodletHapiPlugin = class PodiumPodletHapiPlugin {
constructor() {
Object.defineProperty(this, 'pkg', {
value: pkg,
enumerable: true,
});
}
get [Symbol.toStringTag]() {
return 'PodiumPodletHapiPlugin';
}
register(server, podlet) {
// Run parsers on request and store state object on request.app.podium
server.ext({
type: 'onRequest',
method: async (request, h) => {
const { req, res } = request.raw;
request.app.podium = await podlet.process(req, res);
return h.continue;
},
});
// Set http headers on response
server.ext({
type: 'onPreResponse',
method: (request, h) => {
const response = request.response.output
? request.response.output
: request.response;
response.headers['podlet-version'] = podlet.version;
return h.continue;
},
});
// Decorate response with .podiumSend() method
server.decorate('toolkit', 'podiumSend', fragment => {
return this.request.app.podium.render(fragment);
});
// Mount proxy route
const pathname = utils.pathnameBuilder(
podlet._proxy.pathname,
podlet._proxy.prefix,
'/{path*}',
);
server.route([
{
method: '*',
path: pathname,
handler: async request => {
await podlet._proxy.process(request.app.podium);
return '';
},
},
]);
}
};
module.exports = PodiumPodletHapiPlugin;