forked from TheNoim/fastify-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (56 loc) · 1.94 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
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 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;
return nuxt.render(request.raw, 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',
});