-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
68 lines (64 loc) · 2.29 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
65
66
67
68
const fp = require('fastify-plugin');
const {Nuxt, Builder} = require('nuxt');
const defaults = require('lodash.defaults');
module.exports = fp(/**
@param {fastify.FastifyInstance} fastify
@param {Object} opts
@param {Function} next
**/
function (fastify, opts, next) {
if (!opts.config || typeof opts.config !== 'object') {
return next(new Error('You need to provide a nuxt config.'));
}
const config = opts.config || {};
if (typeof(config.dev) !== typeof(true)) {
config.dev = process.env.NODE_ENV !== 'production';
}
const nuxt = new Nuxt(config);
let attachProperties = [];
if (opts.attachProperties && Array.isArray(opts.attachProperties)) {
attachProperties = opts.attachProperties;
}
let build = true;
let buildPromise = Promise.resolve();
if (config.dev) {
build = false;
buildPromise = new Builder(nuxt).build().then(() => {
build = true;
});
}
fastify.decorate('nuxt', (path, options = {}) => {
if (options.handler && typeof options.handler === 'function') {
options.handler = async (request, reply) => {
if (!build) {
await buildPromise;
}
return await options.handler(request, reply, nuxt);
};
}
const opt = defaults({
method: 'GET',
url: path,
handler: async (request, reply) => {
if (!build) {
await buildPromise;
}
reply.sent = true;
let rq = request.raw;
for (const key of attachProperties) {
if (request[key]) rq[key] = request[key];
}
return nuxt.render(rq, reply.res);
}
}, options);
fastify.route(opt);
}).after(() => {
fastify.nuxt('/_nuxt/*');
fastify.nuxt('/__webpack_hmr/*', {
method: ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
});
});
next();
}, {
fastify: '>=1.0.0',
});