homepage.js/helpers/view_loader.js

40 lines
1.0 KiB
JavaScript
Raw Normal View History

2023-02-13 02:38:15 +01:00
const pug = require('pug');
2023-02-18 14:41:24 +01:00
const fs = require('fs');
2023-02-13 02:16:46 +01:00
const glob = require('glob');
2023-02-18 14:41:24 +01:00
const path = require('path');
2023-02-13 02:16:46 +01:00
const cwd = process.cwd();
const layoutdir = cwd + '/view';
let compiled = {};
async function loadFile(file) {
if (compiled[file]) return compiled[file];
2023-02-13 02:38:15 +01:00
compiled[file] = await pug.compileFile(file);
2023-02-13 02:16:46 +01:00
return compiled[file];
}
2023-02-13 02:38:15 +01:00
async function load(name, data) {
2023-02-18 14:41:24 +01:00
if (!(await exists(name)))
throw new Error("This view does not exist.");
2023-02-13 02:38:15 +01:00
return (await loadFile(layoutdir + '/' + name))(data);
}
2023-02-13 02:16:46 +01:00
2023-02-18 14:41:24 +01:00
async function exists(name) {
return fs.promises.access(layoutdir + '/' + name, fs.constants.R_OK)
.then(() => true)
.catch(() => false);
}
2023-02-13 02:16:46 +01:00
async function preload() {
2023-02-18 14:41:24 +01:00
await glob(layoutdir + '/**/*.pug', (err, files) => {
2023-02-13 02:38:15 +01:00
files.filter(file => {
2023-02-18 14:41:24 +01:00
return !file.startsWith('.') &&
(!fs.lstatSync(file).isDirectory())
2023-02-13 02:38:15 +01:00
}).forEach(file => {
loadFile(file);
});
2023-02-13 02:16:46 +01:00
});
}
2023-02-18 14:41:24 +01:00
module.exports = { load, loadFile, preload, exists }