Skip to content

Commit 52e5115

Browse files
Copilotcharmander
andauthored
Emit deprecation warning instead of throwing for invalid dates
Co-authored-by: charmander <1889843+charmander@users.noreply.github.com>
1 parent 305fe0d commit 52e5115

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

packages/pg/lib/utils.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,10 @@ const prepareValue = function (val, seen) {
5555
}
5656
if (isDate(val)) {
5757
if (isNaN(val.getTime())) {
58-
throw new Error('Cannot convert an invalid date to a string')
58+
process.emitWarning(
59+
'Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.',
60+
'DeprecationWarning'
61+
)
5962
}
6063
if (defaults.parseInputDatesAsUTC) {
6164
return dateToStringUTC(val)

packages/pg/test/unit/utils-tests.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,32 @@ test('prepareValues: 1 BC date prepared properly', function () {
8989
helper.resetTimezoneOffset()
9090
})
9191

92-
test('prepareValues: invalid date throws', function () {
92+
test('prepareValues: invalid date emits deprecation warning', function (done) {
9393
const date = new Date(undefined)
94-
assert.throws(() => utils.prepareValue(date), /invalid date/i)
94+
95+
const warnings = []
96+
const onWarning = (warning) => warnings.push(warning)
97+
process.on('warning', onWarning)
98+
99+
const out = utils.prepareValue(date)
100+
101+
// process.emitWarning defers emission of the 'warning' event to the next tick,
102+
// so give it a chance to fire before asserting on it
103+
setImmediate(() => {
104+
process.removeListener('warning', onWarning)
105+
106+
try {
107+
// still serializes (for backwards compatibility) but warns that this is deprecated
108+
assert.strictEqual(typeof out, 'string')
109+
assert.ok(out.includes('NaN'))
110+
assert.strictEqual(warnings.length, 1)
111+
assert.strictEqual(warnings[0].name, 'DeprecationWarning')
112+
assert.ok(/invalid date/i.test(warnings[0].message))
113+
done()
114+
} catch (e) {
115+
done(e)
116+
}
117+
})
95118
})
96119

97120
test('prepareValues: undefined prepared properly', function () {

0 commit comments

Comments
 (0)