Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,11 @@ And nested ones, too.
<a name="specific"></a>
#### Specific use cases

| Instance | Serialized as |
| -------- | ---------------------------- |
| `Date` | `string` via `toISOString()` |
| `RegExp` | `string` |
| `BigInt` | `integer` via `toString` |
| Instance | Serialized as |
| -------- | ----------------------------------------------------- |
| `Date` | `string` in ISO 8601 format (same as `toISOString()`) |
| `RegExp` | `string` |
| `BigInt` | `integer` via `toString` |

[JSON Schema built-in formats](https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7.3.1) for dates are supported and will be serialized as:

Expand Down
20 changes: 20 additions & 0 deletions benchmark/bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,26 @@ const benchmarks = [
},
input: new Date()
},
{
name: 'Date in a string without format',
schema: {
type: 'string'
},
input: new Date()
},
{
name: 'object with Dates in strings without format',
schema: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' },
createdAt: { type: 'string' },
updatedAt: { type: ['string', 'null'] }
}
},
input: { id: 1, name: 'John Doe', createdAt: new Date(), updatedAt: new Date() }
},
{
name: 'short array of numbers',
schema: {
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1516,7 +1516,7 @@ function buildSingleTypeSerializer (context, location, input) {
if (${input} === null) {
json += JSON_STR_EMPTY_STRING
} else if (${input} instanceof Date) {
json += JSON_STR_QUOTE + ${input}.toISOString() + JSON_STR_QUOTE
json += asDateTime(${input})
} else if (${input} instanceof RegExp) {
json += asString(${input}.source)
} else {
Expand Down
27 changes: 16 additions & 11 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ function asYear (year) {
return null
}

// Quoted ISO 8601 date-time of a Date, the same string as Date.prototype.toISOString()
function asDateTimeString (date) {
const year = asYear(date.getUTCFullYear())
if (year === null) return '"' + date.toISOString() + '"'
const ms = date.getUTCMilliseconds()
return '"' + year +
'-' + TWO_DIGITS[date.getUTCMonth() + 1] +
'-' + TWO_DIGITS[date.getUTCDate()] +
'T' + TWO_DIGITS[date.getUTCHours()] +
':' + TWO_DIGITS[date.getUTCMinutes()] +
':' + TWO_DIGITS[date.getUTCSeconds()] +
'.' + (ms < 10 ? '00' : ms < 100 ? '0' : '') + ms + 'Z"'
}

function escapeStringLoop (str) {
const len = str.length
if (len === 0) {
Expand Down Expand Up @@ -134,16 +148,7 @@ module.exports = class Serializer {
asDateTime (date) {
if (date === null) return '""'
if (date instanceof Date) {
const year = asYear(date.getUTCFullYear())
if (year === null) return '"' + date.toISOString() + '"'
const ms = date.getUTCMilliseconds()
return '"' + year +
'-' + TWO_DIGITS[date.getUTCMonth() + 1] +
'-' + TWO_DIGITS[date.getUTCDate()] +
'T' + TWO_DIGITS[date.getUTCHours()] +
':' + TWO_DIGITS[date.getUTCMinutes()] +
':' + TWO_DIGITS[date.getUTCSeconds()] +
'.' + (ms < 10 ? '00' : ms < 100 ? '0' : '') + ms + 'Z"'
return asDateTimeString(date)
}
if (typeof date === 'string') {
return asString(date)
Expand Down Expand Up @@ -212,7 +217,7 @@ module.exports = class Serializer {
} else if (item === null) {
json += '""'
} else if (item instanceof Date) {
json += '"' + item.toISOString() + '"'
json += asDateTimeString(item)
} else if (item instanceof RegExp) {
json += asString(item.source)
} else {
Expand Down
53 changes: 53 additions & 0 deletions test/date.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,59 @@ test('throw a RangeError for an invalid Date when format is date-time, date or t
}
})

test('render a Date in a string without format as toISOString() for all years', (t) => {
const dates = [
new Date(1674263005800),
dateWithYear(0),
dateWithYear(1, 1, 3, 4, 5, 6, 7),
dateWithYear(999, 5, 15, 23, 59, 59, 50),
dateWithYear(9999, 11, 31, 23, 59, 59, 999),
dateWithYear(-1),
dateWithYear(10000),
new Date(8640000000000000),
new Date(-8640000000000000)
]
const schemas = [
{ type: 'string' },
{ type: 'string', nullable: true },
{ type: ['string', 'null'] },
{ anyOf: [{ type: 'string' }, { type: 'null' }] }
]
t.plan(schemas.length * (dates.length + 1))

for (const schema of schemas) {
const stringify = build(schema)
for (const date of dates) {
t.assert.equal(stringify(date), JSON.stringify(date.toISOString()))
}
t.assert.throws(() => stringify(new Date(NaN)), RangeError)
}
})

test('render a Date subclass in a string without format like format date-time', (t) => {
t.plan(2)

class CustomDate extends Date {
toISOString () { return 'custom' }
}
const date = new CustomDate(1674263005800)

// A toISOString() override is not called, the same as for format: 'date-time'
t.assert.equal(build({ type: 'string' })(date), '"2023-01-21T01:03:25.800Z"')
t.assert.equal(build({ type: 'string', format: 'date-time' })(date), '"2023-01-21T01:03:25.800Z"')
})

test('render Dates in a long string array without format as toISOString()', (t) => {
t.plan(2)

const stringify = build({ type: 'array', items: { type: 'string' } })
const dates = Array.from({ length: 200 }, (_, i) => dateWithYear(i * 61 - 1, i % 12, 1 + i % 28, i % 24, i % 60, i % 60, i))
dates.unshift('first')

t.assert.equal(stringify(dates), JSON.stringify(dates.map((v) => v instanceof Date ? v.toISOString() : v)))
t.assert.throws(() => stringify(['first', ...dates.slice(1), new Date(NaN)]), RangeError)
})

test('render a nested object in a string when type is date-format as ISOString', (t) => {
t.plan(2)

Expand Down
Loading