Newer
Older
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const path = require('path')
const fs = require('fs-jetpack')
const Mustache = require('mustache')
function createPathsFromContext(context = '', filename) {
const { name } = path.parse(filename)
return [
path.join(context, filename),
path.join(context, name),
]
}
function createFileMap(dir, root, ext, debug) {
const cache = {}
const tree = dir.inspectTree(root)
if (tree.type !== 'dir') {
throw new TypeError(`[koa-mustache] viewDir must be an actual directory, found ${ tree.type }`)
}
const processing = tree.children
while (processing.length > 0) {
const current = processing.shift()
if (current.type === 'dir') {
for (const child of current.children) {
child.context = current.context ? path.join(current.context, current.name) : current.name
processing.push(child)
}
} else if (current.type === 'file') {
if (path.extname(current.name) === ext) {
const [pathWithExt, pathWithoutExt] = createPathsFromContext(current.context, current.name)
const content = dir.read(dir.path(root, pathWithExt), 'utf8')
debug(`[koa-mustache] Loading file ${ pathWithExt }`)
Mustache.parse(content)
cache[pathWithExt] = content
cache[pathWithoutExt] = content
}
}
}
return cache
}
module.exports = function createMustacheMiddleware(viewDir, opts = {}) {
const useCache = opts.hasOwnProperty('cache') ? opts.cache : process.env.NODE_ENV === 'production'
const extension = opts.hasOwnProperty('extension') ? opts.extension : '.mustache'
const partialDir = opts.hasOwnProperty('partials') ? opts.partials : 'partials'
const debug = opts.debug || (() => {}) // eslint-disable-line no-empty-function
const viewRoot = fs.cwd(viewDir)
const cache = useCache ? createFileMap(viewRoot, '.', extension, debug) : {}
const partials = createFileMap(viewRoot, partialDir, extension, debug)
return function attachRenderFunc(ctx, next) {
ctx.render = async function renderTemplateData(template, data = {}) {
if (useCache) {
const templateContent = cache[template]
if (templateContent == null) {
this.status = 404
} else {
this.status = 200
this.body = Mustache.render(templateContent, data, partials)
}
} else {
let fileData = await viewRoot.inspectAsync(template)
if (fileData == null) {
template += extension
fileData = await viewRoot.inspectAsync(template)
if (fileData == null) {
this.status = 404
return
}
}
if (fileData.type === 'file') {
const contents = await viewRoot.readAsync(template, 'utf8')
this.status = 200
this.body = Mustache.render(contents, data, partials)
} else {
this.status = 500
}
}
}.bind(ctx)
return next()
}