-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviewAdapter.js
56 lines (50 loc) · 1.52 KB
/
viewAdapter.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
const path = require('path')
const ObjectGet = require('lodash.get')
const FileNotFoundException = require('./FileNotFoundException')
const kAdapter = Symbol('adapter')
const kConfig = Symbol('config')
const kCache = Symbol('cache')
const fs = require('fs')
class ViewAdapter {
constructor($adapter, config) {
this[kAdapter] = $adapter;
this[kConfig] = config;
this[kCache] = Object.create(null)
}
renderFile(file, data, cb) {
this.readFile(this.applyPathPrefix(file), (err, content) => {
if (err) return cb(err)
try {
this[kAdapter].render(content, data, cb)
} catch (err) {
cb(err)
}
})
}
readFile(filename, cb) {
if (this.getConfig('cache')) {
if (this[kCache][filename]) {
return cb(null, this[kCache][filename])
}
}
fs.readFile(filename, 'utf-8', (err, data) => {
if (this.getConfig('cache')) {
this[kCache][filename] = data
}
cb(err, data)
})
}
getConfig(name) {
return ObjectGet(this[kConfig], name, null)
}
getRootPath() {
return this[kConfig]['root'] || ''
}
applyPathPrefix(dest = '') {
return this.applyExtension(path.join(this.getRootPath(), dest.replace(/\./g, '/')))
}
applyExtension(path = '') {
return path + '.' + (this.getConfig('extension') || this.getConfig('engine'))
}
}
module.exports = ViewAdapter