Skip to content

Commit 71a29b8

Browse files
committed
fix JTD serializer for Date objects, fixes #1691
1 parent 001f829 commit 71a29b8

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

lib/compile/jtd/serialize.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ function serializeType(cxt: SerializeCxt): void {
213213
case "timestamp":
214214
gen.if(
215215
_`${data} instanceof Date`,
216-
() => gen.add(N.json, _`${data}.toISOString()`),
216+
() => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`),
217217
() => serializeString(cxt)
218218
)
219219
break

spec/jtd-timestamps.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,16 @@ describe("JTD timestamps", function () {
6767
assert.strictEqual(parseTS('"2021-05-14"')?.toISOString(), "2021-05-14T00:00:00.000Z")
6868
})
6969
})
70+
71+
describe("serializing Date objects", () => {
72+
it("should serialize Date as JSON string", () => {
73+
const schema: JTDSchemaType<Date> = {type: "timestamp"}
74+
const ajv = new _AjvJTD()
75+
const serializeTS = ajv.compileSerializer(schema)
76+
assert.strictEqual(
77+
serializeTS(new Date("2021-05-14T17:59:03.851Z")),
78+
'"2021-05-14T17:59:03.851Z"'
79+
)
80+
})
81+
})
7082
})

0 commit comments

Comments
 (0)