This repository has been archived by the owner on Sep 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
73 lines (61 loc) · 2.06 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
69
70
71
72
73
'use strict'
const fastifyPlugin = require('fastify-plugin')
const { readFile } = require('fs')
const { resolve } = require('path')
const engine = require('pug')
function fastifyPug(fastify, opts, next) {
fastify.decorateReply('locals', {})
fastify.decorateReply('render', render)
fastify.decorateReply('view', render)
const cache = {}
const templatesDir = resolve(opts.views)
const fileEnding = '.pug'
let fallbackTempateDir
if (opts.fallbackViews) {
fallbackTempateDir = resolve(opts.fallbackViews)
}
function render(view, options) {
let locals = { ...opts, ...options }
locals = { ...locals, ...this.locals }
if (typeof opts.filename === 'function') {
locals = { ...locals, filename: opts.filename(view) }
}
if (!view.includes(fileEnding)) {
view += fileEnding
}
const cachedView = cache[view]
if (cachedView && process.env.NODE_ENV === 'production') {
const html = cachedView(locals)
setContentTypeHeader(this)
this.send(html)
} else {
readFile(`${templatesDir}/${view}`, 'utf8', readFileCallback(this, templatesDir, fallbackTempateDir, view, locals))
}
}
function readFileCallback(that, templatesDir, fallbackTempateDir, view, locals) {
return function readFileCallbackInternal(error, template) {
if (error && fallbackTempateDir) {
readFile(`${fallbackTempateDir}/${view}`, 'utf8', readFileCallback(that, templatesDir, null, view, locals))
return
} else if (error) {
that.send(error)
return
}
const compiledTemplate = engine.compile(template, locals)
cache[view] = compiledTemplate
setContentTypeHeader(that)
that.send(compiledTemplate(locals))
}
}
next()
}
function setContentTypeHeader(that) {
if (!that.getHeader('content-type')) {
that.header('Content-Type', 'text/html; charset=UTF-8')
}
}
const metadata = {
fastify: '>=1.0.0',
name: 'fastify-pug'
}
exports = module.exports = fastifyPlugin(fastifyPug, metadata)