Skip to content

Commit

Permalink
fix JTD serializer for Date objects, fixes #1691
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Jul 15, 2021
1 parent 001f829 commit 71a29b8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/compile/jtd/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ function serializeType(cxt: SerializeCxt): void {
case "timestamp":
gen.if(
_`${data} instanceof Date`,
() => gen.add(N.json, _`${data}.toISOString()`),
() => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`),
() => serializeString(cxt)
)
break
Expand Down
12 changes: 12 additions & 0 deletions spec/jtd-timestamps.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,16 @@ describe("JTD timestamps", function () {
assert.strictEqual(parseTS('"2021-05-14"')?.toISOString(), "2021-05-14T00:00:00.000Z")
})
})

describe("serializing Date objects", () => {
it("should serialize Date as JSON string", () => {
const schema: JTDSchemaType<Date> = {type: "timestamp"}
const ajv = new _AjvJTD()
const serializeTS = ajv.compileSerializer(schema)
assert.strictEqual(
serializeTS(new Date("2021-05-14T17:59:03.851Z")),
'"2021-05-14T17:59:03.851Z"'
)
})
})
})

0 comments on commit 71a29b8

Please sign in to comment.