Skip to content

Commit

Permalink
fix(html): avoid rendering [Object object] for undefined values
Browse files Browse the repository at this point in the history
Signed-off-by: KalleV <[email protected]>
  • Loading branch information
KalleV authored and achrinza committed Oct 23, 2024
1 parent 71f84a5 commit 972d410
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
16 changes: 13 additions & 3 deletions lib/send-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ const compiledTemplates = {

module.exports = sendHtml;

const STANDARD_PROPS = ['name', 'statusCode', 'message', 'stack'];

/**
* Sends HTML response to the client.
*
Expand All @@ -24,7 +26,16 @@ module.exports = sendHtml;
* @param {Object} options - The options object.
*/
function sendHtml(res, data, options) {
const toRender = {options, data};
// Filter out properties with undefined / null values and keep standard properties
const filteredData = Object.keys(data).reduce((obj, key) => {
if (data[key] || STANDARD_PROPS.includes(key)) {
obj[key] = data[key];
}
return obj;
}, {});

const toRender = {options, data: filteredData};

// TODO: ability to call non-default template functions from options
const body = compiledTemplates.default(toRender);
sendResponse(res, body);
Expand All @@ -50,8 +61,7 @@ handlebars.registerHelper('partial', partial);
* @returns {string} - The result of the Handlebars template.
*/
function standardProps(prop, options) {
const standardProps = ['name', 'statusCode', 'message', 'stack'];
if (standardProps.indexOf(prop) === -1) {
if (STANDARD_PROPS.indexOf(prop) === -1) {
return options.fn(this);
}
return options.inverse(this);
Expand Down
21 changes: 21 additions & 0 deletions test/handler.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,27 @@ describe('strong-error-handler', function() {
});
});

it('hides undefined properties from the HTML response', function(done) {
const error = new ErrorWithProps({
message: 'A test error message',
details: undefined,
code: undefined,
});
error.statusCode = 400;
givenErrorHandlerForError(error);
requestHTML()
.end(function(err, res) {
expect(res.statusCode).to.eql(400);

const body = res.error.text;

expect(body).to.match(/400(.*?)A test error message/);
expect(body).not.to.match(/details/);
expect(body).not.to.match(/code/);
done();
});
});

function requestHTML(url) {
return request.get(url || '/')
.set('Accept', 'text/html')
Expand Down

0 comments on commit 972d410

Please sign in to comment.