/
index.js
58 lines (44 loc) · 1.38 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
const fs = require('fs')
const jsonld = require('jsonld')
class SimpleRenderer {
constructor (options) {
this.context = {'@vocab': 'http://schema.org/'}
this.vocab = '{}'
this.template = options.template
this.templateError = options.templateError
if (options.context) {
this.context = JSON.parse(fs.readFileSync(options.context).toString())
}
if (options.vocab) {
// parse and stringify for compact form
this.vocab = JSON.stringify(JSON.parse(fs.readFileSync(options.vocab).toString()))
}
this.accept = 'application/ld+json'
}
render (req, res) {
this.renderTemplate(this.template, req, res)
}
error (req, res) {
// use error template if define otherwise template
this.renderTemplate(this.templateError || this.template, req, res)
}
renderTemplate (template, req, res) {
res.locals.statusCode = res.statusCode
res.locals.vocab = this.vocab
let graph = {}
try {
graph = JSON.parse(res.locals.graph)
} catch (e) {}
if (res.locals.jsonldContext) {
graph['@context'] = res.locals.jsonldContext
}
jsonld.promises.compact(graph, this.context).then((compacted) => {
res.locals.graph = JSON.stringify(compacted)
res.render(template)
}).catch((err) => {
console.error(err.stack || err.message)
res.render(template)
})
}
}
module.exports = SimpleRenderer