UNPKG

1.43 kBJavaScriptView Raw
1const fs = require('fs'),
2 logger = require('./logger'),
3 path = require('path'),
4 mustache = require('mustache');
5
6const tags = ['<%=', '=%>'];
7const allowedTemplateExtentions = ['.css', '.js', '.liquid', '.yml', '.xml', '.json', '.svg', '.graphql', '.html'];
8
9/**
10 * This function will replace tags with values from template data.
11 * Example: if tags are <%= and =%> and we have code like this:
12 *
13 * ---
14 * slug: <%= page_url =%>
15 * ---
16 *
17 * This function will replace `page_url` with value from templateData
18 * hash or it will **not** raise an error if the value is missing.
19 * @param {string} path - path to the file which will be processed.
20 **/
21const fillInTemplateValues = (filePath, templateData) => {
22 const fileBody = fs.readFileSync(filePath, 'utf8');
23 if (qualifedForTemplateProcessing(filePath) && hasTemplateValues(templateData)) {
24 try {
25 return mustache.render(fileBody, templateData, {}, tags);
26 } catch (err) {
27 logger.Debug(err);
28 return fileBody;
29 }
30 } else {
31 return fs.createReadStream(filePath);
32 }
33};
34
35const qualifedForTemplateProcessing = (filePath) => {
36 return allowedTemplateExtentions.includes(path.extname(filePath));
37};
38
39const hasTemplateValues = (templateData) => {
40 try {
41 return Object.keys(templateData).length !== 0;
42 } catch (err) {
43 logger.Debug(err);
44 return false;
45 }
46};
47
48module.exports = {
49 fillInTemplateValues: fillInTemplateValues
50};