1 | import compile from 'es6-template-strings/compile'
|
2 | import fs from 'fs'
|
3 | import path from 'path'
|
4 | import ServerRenderer from 'render/ServerRenderer'
|
5 |
|
6 | let logger = global.Logger.getLogger('SimpleHtmlRenderer')
|
7 |
|
8 | class SimpleHtmlRenderer extends ServerRenderer {
|
9 | constructor (options) {
|
10 | super()
|
11 | this._options = options
|
12 | this._pageCache = {}
|
13 | }
|
14 |
|
15 | _loadHtml (htmlPath, callback) {
|
16 | logger.info('[RENDERING]', htmlPath)
|
17 | fs.readFile(htmlPath, (err, data) => {
|
18 | if (err) {
|
19 | callback(err, null)
|
20 | } else {
|
21 | let start = new Date().getTime()
|
22 | let htmlTemplate = compile(data.toString())
|
23 | let end = new Date().getTime()
|
24 | let elapsed = end - start
|
25 | logger.info('[TEMPLATE_COMPILATION] Finish compiling ' + htmlPath + ', elapsed: ' + elapsed + 'ms')
|
26 | if (this._options.cache) {
|
27 | logger.info('[TEMPLATE_CACHING] Caching ' + htmlPath)
|
28 | this._pageCache[htmlPath] = htmlTemplate
|
29 | }
|
30 | end = new Date().getTime()
|
31 | elapsed = end - start
|
32 | logger.info('[FINISH_RENDERING] ' + htmlPath + ' in: ' + elapsed + 'ms')
|
33 | callback(null, htmlTemplate)
|
34 | }
|
35 | })
|
36 | }
|
37 |
|
38 | render (file, callback) {
|
39 | let basePath = this._options.path
|
40 | let finalPath = path.join(basePath, file)
|
41 | if (this._pageCache[finalPath] == null || typeof this._pageCache[finalPath] === 'undefined') {
|
42 | this._loadHtml(finalPath, callback)
|
43 | } else {
|
44 | callback(null, this._pageCache[finalPath])
|
45 | }
|
46 | }
|
47 | }
|
48 |
|
49 | export default SimpleHtmlRenderer
|