-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtemplate.js
64 lines (56 loc) · 1.89 KB
/
template.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
59
60
61
62
63
64
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
class Template {
constructor(app) {
this.dir = app.templatesDir;
this.logger = app.logger;
}
load() {
this.logger.info(
'Template -> loading request templates from: ' + this.dir
);
const dirents = fs.readdirSync(this.dir, {
withFileTypes: true,
});
const filesNames = dirents
.filter((dirent) => dirent.isFile())
.map((dirent) => dirent.name);
let templates = [];
let dynamicTemplates = [];
let specialTemplates = [];
for (let index = 0; index < filesNames.length; index++) {
const template = filesNames[index];
let ext = path.extname(template);
if (ext == '.js') {
//dynamically loaded js
//add the filename to be required later
dynamicTemplates.push(this.dir + '/' + template);
continue;
}
if (ext != '.yaml' && ext != '.yml') continue; //unsupported file format
try {
let doc = yaml.load(
fs.readFileSync(this.dir + '/' + template, 'utf8')
);
this.logger.info(
'Template -> loading template: ' + template + ' success '
);
if (template == '404.yaml' || template == '404.yml') {
specialTemplates.push(doc);
continue;
}
templates.push(doc);
} catch (e) {
throw new Error(
'Failed loading template: ' + template + ': ' + e
);
}
}
return {
templates: [...templates, ...specialTemplates],
dynamicTemplates,
};
}
}
module.exports = Template;