When `asString` receives `undefined` an exception is thrown
Opened this issue · 2 comments
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.24.3
Plugin version
5.9.1
Node.js version
20.2.0
Operating system
Linux
Operating system version (i.e. 20.04, 11.3, 10)
Ubuntu 22.04.1
Description
Not entirely sure this is a bug, could be intended behavior.
I have an array of stings, however one of the elements is undefined
.
['test1', 'test2', 'test3', undefined]
If I return that from a fastify endpoint, asString
throws an exception:
TypeError: Cannot read properties of undefined (reading 'toString')
at Serializer.asString (/repo/node_modules/fast-json-stringify/lib/serializer.js:113:19)
at anonymous1 (eval at build (/repo/node_modules/fast-json-stringify/index.js:190:23), <anonymous>:17:28)
at anonymous0 (eval at build (/repo/node_modules/fast-json-stringify/index.js:190:23), <anonymous>:52:19)
at serialize (/repo/node_modules/fastify/lib/reply.js:896:12)
at preSerializationHookEnd (/repo/node_modules/fastify/lib/reply.js:516:17)
at preSerializationHook (/repo/node_modules/fastify/lib/reply.js:500:5)
at Reply.send (/repo/node_modules/fastify/lib/reply.js:204:7)
at /repo/node_modules/fastify/lib/wrapThenable.js:25:15
Steps to Reproduce
export default async (app: FastifyInstance) => {
app.route({
method: 'GET',
url: '/test',
schema: {
response: {
200: {
type: 'object',
properties: {
status: { type: 'string' },
message: { type: 'string' },
testArray: {
type: 'array',
items: { type: 'string' }
}
}
}
}
},
handler: async () => {
return {
status: 'ok',
message: 'This is a test route',
testArray: ['test1', 'test2', 'test3', undefined]
}
}
})
}
Expected Behavior
It seems that asString
will default the input to an empty string if its null
.
fast-json-stringify/lib/serializer.js
Line 103 in 74c35c0
I can confirm this behavior by sending ['test1', 'test2', 'test3', null]
instead. No error is thrown, and my response looks like the following:
{
"status": "ok",
"message": "This is a test route",
"testArray": [
"test1",
"test2",
"test3",
""
]
}
I'm thinking that asString
should check for undefined
as well. However I understand that this may technically be incorrect because my response schema defines an array of strings, not Array<string | undefined>
.
Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.
Absolutely! I've opened pr #681. Not sure if I did that correctly sorry in advanced