|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const fp = require('fastify-plugin') |
| 4 | +const fs = require('fs') |
| 5 | +const path = require('path') |
| 6 | +const HLRU = require('hashlru') |
| 7 | +const supportedEngines = ['ejs', 'pug', 'handlebars'] |
| 8 | + |
| 9 | +function fastifyView (fastify, opts, next) { |
| 10 | + fastify.decorateReply('view', view) |
| 11 | + |
| 12 | + if (!opts.engine) { |
| 13 | + next(new Error('Missing engine')) |
| 14 | + return |
| 15 | + } |
| 16 | + |
| 17 | + const type = Object.keys(opts.engine)[0] |
| 18 | + if (supportedEngines.indexOf(type) === -1) { |
| 19 | + next(new Error(`'${type}' not yet supported, PR? :)`)) |
| 20 | + return |
| 21 | + } |
| 22 | + |
| 23 | + const engine = opts.engine[type] |
| 24 | + const options = opts.options || {} |
| 25 | + const templatesDir = path.join(process.cwd(), opts.templates || './') |
| 26 | + const lru = HLRU(opts.maxCache || 100) |
| 27 | + const prod = process.env.NODE_ENV === 'production' |
| 28 | + |
| 29 | + function view (page, data) { |
| 30 | + if (!page || !data) { |
| 31 | + this.send(new Error('Missing data')) |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + const toHtml = lru.get(page) |
| 36 | + |
| 37 | + if (toHtml && prod) { |
| 38 | + this.header('Content-Type', 'text/html').send(toHtml(data)) |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + fs.readFile(path.join(templatesDir, page), 'utf8', readCallback(this, page, data)) |
| 43 | + } |
| 44 | + |
| 45 | + function readCallback (that, page, data) { |
| 46 | + return function _readCallback (err, html) { |
| 47 | + if (err) { |
| 48 | + that.send(err) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + lru.set(page, engine.compile(html, options)) |
| 53 | + that.header('Content-Type', 'text/html').send(lru.get(page)(data)) |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + next() |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = fp(fastifyView, '>=0.13.1') |
0 commit comments