fix: handle invalid date objects in jsonify stringify (#2851)
## Summary
- Handles the case when `Date.toISOString()` throws for invalid dates by
catching the error and serializing as `"Invalid Date"`
- Round-trips correctly: `new Date("Invalid Date")` serializes to
`["Date","Invalid Date"]` and deserializes back to an invalid `Date`
object
- Adds test case and snapshot for invalid `Date`
Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
This commit is contained in:
co-authored by
Bartek Iwańczuk
parent
61eb5f625a
commit
b11d1d98f2
@@ -44,6 +44,8 @@ snapshot[`round trip - URL {\\n href: 'https://fresh.deno.dev/',\\n origin: 'h
|
||||
|
||||
snapshot[`round trip - 1990-05-31T00:00:00.000Z 1`] = `'[["Date","1990-05-31T00:00:00.000Z"]]'`;
|
||||
|
||||
snapshot[`round trip - Invalid Date 1`] = `'[["Date","Invalid Date"]]'`;
|
||||
|
||||
snapshot[`round trip - Map(2) { 1 => null, undefined => -2 } 1`] = `'[["Map",[1,-2,-1,2]],1,-2]'`;
|
||||
|
||||
snapshot[`round trip - Set(5) { 1, 2, null, -2, NaN } 1`] = `'[["Set",[1,2,-2,3,-3]],1,2,-2]'`;
|
||||
|
||||
@@ -34,6 +34,7 @@ const TESTS = [
|
||||
new Uint8Array([1, 2, 3]),
|
||||
new URL("https://fresh.deno.dev"),
|
||||
new Date("1990-05-31"),
|
||||
new Date("Invalid Date"),
|
||||
new Map([[1, null], [undefined, -2]]),
|
||||
new Set([1, 2, null, -2, NaN]),
|
||||
[1, , 3],
|
||||
|
||||
@@ -108,7 +108,13 @@ function serializeInner(
|
||||
if (value instanceof URL) {
|
||||
str += `["URL","${value.href}"]`;
|
||||
} else if (value instanceof Date) {
|
||||
str += `["Date","${value.toISOString()}"]`;
|
||||
let iso: string;
|
||||
try {
|
||||
iso = value.toISOString();
|
||||
} catch {
|
||||
iso = "Invalid Date";
|
||||
}
|
||||
str += `["Date","${iso}"]`;
|
||||
} else if (value instanceof RegExp) {
|
||||
str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`;
|
||||
} else if (value instanceof Uint8Array) {
|
||||
|
||||
Reference in New Issue
Block a user