2016-05-27 15:04:20 +00:00
|
|
|
// Copyright IBM Corp. 2016. All Rights Reserved.
|
|
|
|
// Node module: strong-error-handler
|
|
|
|
// This file is licensed under the MIT License.
|
|
|
|
// License text available at https://opensource.org/licenses/MIT
|
|
|
|
|
2016-08-17 19:03:17 +00:00
|
|
|
'use strict';
|
2019-10-11 13:57:15 +00:00
|
|
|
const ejs = require('ejs');
|
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
2016-05-27 15:04:20 +00:00
|
|
|
|
2019-10-11 13:57:15 +00:00
|
|
|
const assetDir = path.resolve(__dirname, '../views');
|
|
|
|
const compiledTemplates = {
|
2016-05-27 15:04:20 +00:00
|
|
|
// loading default template and stylesheet
|
|
|
|
default: loadDefaultTemplates(),
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = sendHtml;
|
|
|
|
|
|
|
|
function sendHtml(res, data, options) {
|
2020-05-20 21:33:11 +00:00
|
|
|
const toRender = {options, data};
|
2016-05-27 15:04:20 +00:00
|
|
|
// TODO: ability to call non-default template functions from options
|
2019-10-11 13:57:15 +00:00
|
|
|
const body = compiledTemplates.default(toRender);
|
2020-05-20 21:33:11 +00:00
|
|
|
sendResponse(res, body);
|
2016-05-27 15:04:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Compile and cache the file with the `filename` key in options
|
|
|
|
*
|
|
|
|
* @param filepath (description)
|
|
|
|
* @returns {Function} render function with signature fn(data);
|
|
|
|
*/
|
|
|
|
function compileTemplate(filepath) {
|
2019-10-11 13:57:15 +00:00
|
|
|
const options = {cache: true, filename: filepath};
|
|
|
|
const fileContent = fs.readFileSync(filepath, 'utf8');
|
2016-05-27 15:04:20 +00:00
|
|
|
return ejs.compile(fileContent, options);
|
|
|
|
}
|
|
|
|
|
|
|
|
// loads and cache default error templates
|
|
|
|
function loadDefaultTemplates() {
|
2019-10-11 13:57:15 +00:00
|
|
|
const defaultTemplate = path.resolve(assetDir, 'default-error.ejs');
|
2016-05-27 15:04:20 +00:00
|
|
|
return compileTemplate(defaultTemplate);
|
|
|
|
}
|
|
|
|
|
2020-05-20 21:33:11 +00:00
|
|
|
function sendResponse(res, body) {
|
2016-05-27 15:04:20 +00:00
|
|
|
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
|
|
res.end(body);
|
|
|
|
}
|