-
-
Notifications
You must be signed in to change notification settings - Fork 209
Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Fastify version
4.2.1
Plugin version
5.1.0
Node.js version
18.4.0
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
12.4
Description
The generated code for creating strings from objects checks for the existence of a toString
function, but through Object.hasOwnProperty.call(object, 'toString') (https://github.com/fastify/fast-json-stringify/blob/master/index.js#L904). This does not work for class instances.
An example for where this goes south: if you're using Luxon DateTimes in your code for dates instead of the regular JavaScript Date object and need it as a string in your API response, the conversion fails (but the error message references a stringified Luxon DateTime because there is a toString present on the class, just not as a "own property".
Steps to Reproduce
dependencies:
npm install fastify@4 luxon@3
index.js:
const l = require('luxon')
const f = require('fastify')
const app = new f.fastify()
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
date: { type: 'string', format: 'date-time' }
}
}
}
}
}
app.get('/', opts, () => {
return { date: l.DateTime.now() }
})
app.listen({ port: 8000 })
call route
curl localhost:8000
error:
{"statusCode":500,"error":"Internal Server Error","message":"The value \"2022-07-13T16:03:06.938+02:00\" does not match schema definition."}
Note that the value reported is a valid date-time string
Expected Behavior
The string conversion should succeed by calling toString() on the instance.