Skip to content

Commit be504a6

Browse files
committed
Fix: Handle invalid dates in serialization
1 parent 9174783 commit be504a6

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

packages/pg/lib/utils.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,14 @@ function prepareObject(val, seen) {
9393
}
9494

9595
function dateToString(date) {
96+
// Validate date to prevent serialization of invalid dates as "NaN-NaN-NaN..."
97+
// Invalid dates can occur from new Date(undefined), new Date(NaN), etc.
98+
// See https://github.com/brianc/node-postgres/issues/3318
99+
if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
100+
throw new TypeError('Cannot serialize invalid date');
101+
}
102+
96103
let offset = -date.getTimezoneOffset()
97-
98104
let year = date.getFullYear()
99105
const isBCYear = year < 1
100106
if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation
@@ -127,6 +133,13 @@ function dateToString(date) {
127133
}
128134

129135
function dateToStringUTC(date) {
136+
// Validate date to prevent serialization of invalid dates as "NaN-NaN-NaN..."
137+
// Invalid dates can occur from new Date(undefined), new Date(NaN), etc.
138+
// See https://github.com/brianc/node-postgres/issues/3318
139+
if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
140+
throw new TypeError('Cannot serialize invalid date');
141+
}
142+
130143
let year = date.getUTCFullYear()
131144
const isBCYear = year < 1
132145
if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation

0 commit comments

Comments
 (0)