Description
TL;DR: Let's add a new option: --transform
to allow for alternative data transformation and validation.
Is your feature request related to a problem? Please describe.
When a client and a server interact, there is always the task of checking the data to ensure that it complies with the agreed protocol. Typescript doesn't do run-time checks. And we cannot rely on the data validity just because we so typed them.
That's why there is currently a JavaScript layer of functions like <ModelName>FromJSONTyped()
that ensure the data structure. It's a simple data sanitizer and validator.
However, currently we don't have an option to replace this layer with another one. Like, for example, with a real validator lilbrary.
Describe the solution you'd like
There are specialized solutions for data validation e.g.: Zod, Yup, io-ts, ArkType and others.
They are all - model-first species. I.e. they take model declarations and give us back types and JS run-time that can validate and transform data.
This is a proposition of adding a new option to the generator along with the presently existing --platform
and --framework
. It can be named like --data-transformer
or just --transform
.
We can call the existing sanitizer as default
. More will come: zod
, yup
etc.
Having this in place we could start creating new branches in the mustache templates.
For example, instead of generating interfaces:
export interface User {
name?: string
}
we can start generating models:
import y from "yup"
export const userSchema = y.object({
name: y.string()
})
export type User = y.InferType<typeof userSchema>
And instead of invoking the current sanitizer:
return new runtime.JSONApiResponse(response, (jsonValue) => ModelNameRespFromJSON(jsonValue));
we can run the model's validator:
return new runtime.JSONApiResponse(response, async (jsonValue) => await modelNameSchema.validate(jsonValue));
Why --transform
and not --validate
?
Why --transform
and not --validate
?
Because validation doesn't assume transformation, while the reverse would be fine. A simple read-only validation can be considered as a 1:1 transformation with a "side-effect" of checking data. Besides, we may want to transform data by defaulting missing values for example without actual validation.
Describe alternatives you've considered
None
Additional context
My true intention goes beyond the designated validators. I would like to use it for mobx-state-tree models. As a validator, it may not be that sophisticated, but its models - are observable state components out-of-the-box, so to speak. They can be extended further easily.
Here is a sandbox with an example of possible usage.