Refactor web server and release workflow
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const Handlebars = require('handlebars');
|
||||
|
||||
const VIEWS_ROOT = path.join(__dirname, 'views');
|
||||
const cache = new Map();
|
||||
|
||||
Handlebars.registerHelper('eq', function (left, right) {
|
||||
return left === right;
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('playerUrl', function (slug) {
|
||||
const base = (process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
|
||||
return `${base}/screen/${encodeURIComponent(slug)}`;
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('json', function (value) {
|
||||
return new Handlebars.SafeString(JSON.stringify(value).replace(/</g, '\\u003c'));
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('usernameInitial', function (username) {
|
||||
const value = String(username || '').trim();
|
||||
if (!value) {
|
||||
return 'A';
|
||||
}
|
||||
return value.charAt(0).toUpperCase();
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('userInitial', function (name, username) {
|
||||
const value = String(name || '').trim() || String(username || '').trim();
|
||||
if (!value) {
|
||||
return 'A';
|
||||
}
|
||||
return value.charAt(0).toUpperCase();
|
||||
});
|
||||
|
||||
function loadTemplate(relativePath) {
|
||||
const filePath = path.join(VIEWS_ROOT, relativePath);
|
||||
const stat = fs.statSync(filePath);
|
||||
const cached = cache.get(filePath);
|
||||
if (cached && cached.mtimeMs === stat.mtimeMs) {
|
||||
return cached.template;
|
||||
}
|
||||
const template = Handlebars.compile(fs.readFileSync(filePath, 'utf8'));
|
||||
cache.set(filePath, { mtimeMs: stat.mtimeMs, template: template });
|
||||
return template;
|
||||
}
|
||||
|
||||
function renderView(viewName, context) {
|
||||
const viewContext = Object.assign({ stylesheets: [], scripts: [] }, context || {});
|
||||
const page = loadTemplate(`${viewName}.hbs`);
|
||||
const layout = loadTemplate(path.join('layout.hbs'));
|
||||
const body = page(viewContext);
|
||||
return layout(Object.assign({}, viewContext, { body: body }));
|
||||
}
|
||||
|
||||
function renderFragment(viewName, context) {
|
||||
const viewContext = Object.assign({ stylesheets: [], scripts: [] }, context || {});
|
||||
const page = loadTemplate(`${viewName}.hbs`);
|
||||
const layout = loadTemplate(path.join('frame-layout.hbs'));
|
||||
const body = page(viewContext);
|
||||
return layout(Object.assign({}, viewContext, { body: body }));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
renderView,
|
||||
renderFragment
|
||||
};
|
||||
Reference in New Issue
Block a user