-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.js
58 lines (49 loc) · 1.65 KB
/
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
'use strict';
const Inert = require('@hapi/inert');
const Url = require('url');
const Path = require('path');
const Package = require('./package.json');
const internals = {};
module.exports = {
name: Package.name,
register: async (server) => {
await server.register(Inert);
server.route({
method: 'GET',
path: '/{path*}',
config: {
id: 'catchall',
handler: {
directory: {
path: Path.join(__dirname, 'build'),
listing: false,
index: true
}
}
}
});
//fiddle with requests to make this work as a hapi plugin with
//the React History API
server.ext({
type: 'onRequest',
method: (request, h) => {
const route = request.server.match(request.method, request.path);
const noOtherRoute = !route || route.settings.id === 'catchall';
const isGet = request.method === 'get';
const takesHtml = internals.takesHtml(request.headers.accept);
const looksLikeFile = request.path.indexOf('.') !== -1;
if (noOtherRoute && !looksLikeFile && isGet && takesHtml) {
request.setUrl('/');
request.raw.req.url = Url.format(request.url);
}
return h.continue;
}
});
}
};
internals.takesHtml = accept => {
if (!accept) {
return false;
}
return accept.indexOf('text/html') !== -1 || accept.indexOf('*/*') !== -1;
};