From 5181ca710feee5f6e6be7dba78fb93838dc21214 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Tue, 11 May 2021 16:07:55 +0100 Subject: [PATCH] Fixing an issue with date objects not being managed by handlebars correctly. --- packages/string-templates/src/index.cjs | 5 ++--- packages/string-templates/src/utilities.js | 19 ++++++++++++++++--- packages/string-templates/test/basic.spec.js | 6 ++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/packages/string-templates/src/index.cjs b/packages/string-templates/src/index.cjs index e662f253c6..b62521942a 100644 --- a/packages/string-templates/src/index.cjs +++ b/packages/string-templates/src/index.cjs @@ -4,7 +4,7 @@ const processors = require("./processors") const { cloneDeep } = require("lodash/fp") const { removeNull, - addConstants, + updateContext, removeHandlebarsStatements, } = require("./utilities") const manifest = require("../manifest.json") @@ -92,8 +92,7 @@ module.exports.processStringSync = (string, context) => { } // take a copy of input incase error const input = string - let clonedContext = removeNull(cloneDeep(context)) - clonedContext = addConstants(clonedContext) + const clonedContext = removeNull(updateContext(cloneDeep(context))) // remove any null/undefined properties if (typeof string !== "string") { throw "Cannot process non-string types." diff --git a/packages/string-templates/src/utilities.js b/packages/string-templates/src/utilities.js index b33e8bfe1d..3b1addf316 100644 --- a/packages/string-templates/src/utilities.js +++ b/packages/string-templates/src/utilities.js @@ -26,11 +26,24 @@ module.exports.removeNull = obj => { return obj } -module.exports.addConstants = obj => { +module.exports.updateContext = obj => { if (obj.now == null) { - obj.now = new Date() + obj.now = (new Date()).toISOString() } - return obj + function recurse(obj) { + for (let key of Object.keys(obj)) { + if (!obj[key]) { + continue + } + if (obj[key] instanceof Date) { + obj[key] = obj[key].toISOString() + } else if (typeof obj[key] === "object") { + obj[key] = recurse(obj[key]) + } + } + return obj + } + return recurse(obj) } module.exports.removeHandlebarsStatements = string => { diff --git a/packages/string-templates/test/basic.spec.js b/packages/string-templates/test/basic.spec.js index 5732181b13..f5c7c8be75 100644 --- a/packages/string-templates/test/basic.spec.js +++ b/packages/string-templates/test/basic.spec.js @@ -107,6 +107,12 @@ describe("check the utility functions", () => { const property = makePropSafe("thing") expect(property).toEqual("[thing]") }) + + it("should be able to handle an input date object", async () => { + const date = new Date() + const output = await processString("{{ dateObj }}", { dateObj: date }) + expect(date.toISOString()).toEqual(output) + }) }) describe("check manifest", () => {