feat: custom schema extension #669
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
This PR adds support for parsing custom schema extension with
parserExtensions
option. This is not based on any concrete issue but just on my personal problem that I'm trying to solve. For context:Problem
We use
@sinclair/typebox
+json-schema-to-typescript
to share types between services and we have some non-standard schemas. Specifically, we commonly usetypebox
'es "Javascript constructs" likeType.Function
.Let's say I have this
In this
compile
will just default toCUSTOM_TYPE
which makes sense.Currently we hack around this issue with
tsType
like sowhich gets us the correct type.
While this, works you can already start to feel that we're doing some duplicated work which might be very error prone (
Type.String
andType.Number
are already handled byjson-schema-to-typescript
). Add one more level to the schema andtsType
just becomes not worth it for usSolution
Added
parserExtensions
option that allows defining a custom compile callback for unsupportedtype
. Whentype
matches, it runs the callback. Callback provides the currentschema
that's being parsed andcompileSchema
callback to basically pass the parsing back to the library.Simple example
results in
Complicated example (with the mentioned
Type.Function
)results in
Side Note
I'm well aware that I need to add tests. Willing to do that add and fix any concerns. Want to validate first if the idea is even welcome though 🙏, @bcherny.