Skip to content

Commit 577479d

Browse files
committed
Partial work - need to load config from somewhere
1 parent be10930 commit 577479d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

lib/utils.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ module.exports.pathBasename = pathBasename
55
module.exports.getFullUri = getFullUri
66
module.exports.hasSuffix = hasSuffix
77
module.exports.parse = parse
8+
module.exports.processHandlebarFile = processHandlebarFile
89
module.exports.serialize = serialize
910
module.exports.translate = translate
1011
module.exports.stringToStream = stringToStream
@@ -19,6 +20,8 @@ const path = require('path')
1920
const $rdf = require('rdflib')
2021
const from = require('from2')
2122
const url = require('url')
23+
const Handlebars = require('handlebars')
24+
const debug = require('./debug').errors
2225

2326
/**
2427
* Returns a fully qualified URL from an Express.js Request object.
@@ -147,6 +150,54 @@ function parse (data, baseUri, contentType, callback) {
147150
}
148151
}
149152

153+
/**
154+
* Reads a file, processes it (performing template substitution), and saves
155+
* back the processed result.
156+
*
157+
* @param filePath {string}
158+
* @param substitutions {Object}
159+
*
160+
* @return {Promise}
161+
*/
162+
async function processHandlebarFile (filePath, substitutions) {
163+
return new Promise((resolve, reject) => {
164+
fs.readFile(filePath, 'utf8', (error, rawSource) => {
165+
if (error) {
166+
return reject(error)
167+
}
168+
169+
const output = processHandlebarTemplate(rawSource, substitutions)
170+
171+
fs.writeFile(filePath, output, (error) => {
172+
if (error) {
173+
return reject(error)
174+
}
175+
resolve()
176+
})
177+
})
178+
})
179+
}
180+
181+
/**
182+
* Performs a Handlebars string template substitution, and returns the
183+
* resulting string.
184+
*
185+
* @see https://www.npmjs.com/package/handlebars
186+
*
187+
* @param source {string} e.g. 'Hello, {{name}}'
188+
*
189+
* @return {string} Result, e.g. 'Hello, Alice'
190+
*/
191+
function processHandlebarTemplate (source, substitutions) {
192+
try {
193+
const template = Handlebars.compile(source)
194+
return template(substitutions)
195+
} catch (error) {
196+
debug(`Error processing template: ${error}`)
197+
return source
198+
}
199+
}
200+
150201
function serialize (graph, baseUri, contentType, callback) {
151202
try {
152203
// target, kb, base, contentType, callback

0 commit comments

Comments
 (0)