[disscussion] why not use zod?
Closed this issue · 2 comments
yolio2003 commented
the farrow schema is good to started, but seems not find the enum and some thing like transform ...
and the question is
- how to define a enum data struct?
- maybe can get some docs for how it(code gen) works?
thx!
Lucifier129 commented
zod
and other schema-builder are not well for codegen
and seamless recursive schema support.
For enum
you can juse use Union
instead.
And farrow-schema
is limited itself for just type-check without other validation logic support like max
, range
which can't be codegen
in type level.
For more validation support, user can extend Schema
to add custom verify rules but they can not be used to build request/response schema
in farrow-api
, they can only be used in the middleware function in server side.
import { RegExp } from 'farrow-schema/validator';
/**
* custom validator without codegen support
*/
const Reg0 = RegExp(/123/);
const validateReg0 = createSchemaValidator(Reg0);
const definition = {
input: {
[Type]: String,
},
output: {
[Type]: Int,
},
};
const incre = Api(definition, (input: string): number => {
// use in server side
const result = validateReg0(input);
if (result.isOk) {
return 123
} else {
return 0
}
});
// more complex custom schema
class DateType extends ValidatorType<Date> {
validate(input: unknown) {
if (input instanceof Date) {
return this.Ok(input)
}
if (typeof input === 'number' || typeof input === 'string') {
return this.Ok(new Date(input))
}
return this.Err(`${input} is not a valid date`)
}
}
class EmailType extends ValidatorType<string> {
validate(input: unknown) {
if (typeof input !== 'string') {
return this.Err(`${input} should be a string`)
}
if (/^example@farrow\.com$/.test(input)) {
return this.Ok(input)
}
return this.Err(`${input} is not a valid email`)
}
}
// now user can not be used in request/response too
const User = Struct({
name: String,
email: EmailType,
createAt: DateType,
})
const validateUser = createSchemaValidator(User)
yolio2003 commented
ok got that, thx master!