Closed tzezar closed 3 months ago
@tzezar Hi,
When using Fastify, you shouldn't use Type.Date. TypeBox added this type as an extended type, but the schema it produces is unknown to Ajv (which is the validator Fastify uses internally). The issue stems from Json Schema (and Json) being unable to encode JavaScript Date objects, and that dates need to be encoded as either number
or string
(iso8601). For this reason, you should define the schema as either Type.Number (timestamp) or Type.String (iso8601)
If you're using https://github.com/fastify/fastify-type-provider-typebox, unfortunately you won't be able to use Type.Transform as this is only applicable to TypeBox's validators (specifically the Encode / Decode functions). There are ways to integrate Encode/Decode into the Fastify validation pipeline, but as of today, the Encode/Decode hasn't been integrated into the Fastify type provider project (so if you want to use these Transform types, you will need to implement them manually).
From memory, you will need to override via the setValidationCompiler
and preValidationHook
handler. It looks like I've drafted an experimental implementation of Encode/Decode which is noted at the following issue comment.
https://github.com/fastify/fastify-type-provider-typebox/issues/128#issuecomment-1960644297
I may take a look at providing the Type Provider project a more fleshed out implementation later in the year, but if you do try out the implementation noted on this comment thread and it works good for you, feel free to submit a PR to the provider project, ill be able to help review the PR.
Hope this helps. S
@tzezar Hey, might close off this issue as it's generally related to Fastify (and Drizzle) integration.
I can only really speak for Fastify integrations (as that project I've had experience with). But as a general rule, when working with projects that are based on the Json Schema specification, only use the [Json]
types and avoid the [JavaScript]
types (as the latter will only work with TypeBox validators). The types listed for either category can be found here.
https://github.com/sinclairzx81/typebox?tab=readme-ov-file#types-json https://github.com/sinclairzx81/typebox?tab=readme-ov-file#javascript-types
If you have any follow up questions, feel free to ping on this thread. Cheers S
I encountered a problem. Using querybuilders e.g. drizzle the timestamp field from postgresql has a Date type. Specifically Date | null. When creating a schema for the response body, fastify spits out an error that I don't understand too much, and the answer found in another post doesn't work.
I will show you some code to give context to this problem.
results type:
route schema:
response schema type (the same as results I provide to handler)
and problem comes probably from this part:
createdAt: Type.Union([Type.Date(), Type.Null()]),
I tried some solutions from simmilar topic I found:
but I failed doing so.
Finally the error I receive in the console: