Validate using AJV, parse using typebox #1051
-
Hello, Is it possible to validate using AJV by passing the JSON schema generated by typebox while still parsing with typebox? My use case is that I have some advanced schemas that are not supported out of the box with typebox. (For example Is it recommended that I do something like this?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@RobinVdBroeck Hi,
Yes, this is fine. The Value.* functions can be used to provide additional functionality over Ajv. For parsing, it is recommended to implement a series of Value.* calls in a pipeline. The following is how TypeBox implements Parse internally. https://github.com/sinclairzx81/typebox/blob/master/src/value/parse/parse.ts#L38-L68 // ------------------------------------------------------------------
// ParseReducer
// ------------------------------------------------------------------
type ReducerFunction = (schema: TSchema, references: TSchema[], value: unknown) => unknown
// prettier-ignore
const ParseReducer: ReducerFunction[] = [
(_schema, _references, value) => Clone(value),
(schema, references, value) => Default(schema, references, value),
(schema, references, value) => Clean(schema, references, value),
(schema, references, value) => Convert(schema, references, value),
// replace Assert() with ajv.validate() and throw on error
(schema, references, value) => { Assert(schema, references, value); return value },
(schema, references, value) => (HasTransform(schema, references) ? TransformDecode(schema, references, value) : value),
]
// ------------------------------------------------------------------
// ParseValue
// ------------------------------------------------------------------
function ParseValue<T extends TSchema, R = StaticDecode<T>>(schema: T, references: TSchema[], value: unknown): R {
return ParseReducer.reduce((value, reducer) => reducer(schema, references, value), value) as R
} You can copy and paste the above to construct your own pipeline using Ajv (and add and remove additional processing stages as necessary) Hope this helps |
Beta Was this translation helpful? Give feedback.
@RobinVdBroeck Hi,
Yes, this is fine. The Value.* functions can be used to provide additional functionality over Ajv. For parsing, it is recommended to implement a series of Value.* calls in a pipeline. The following is how TypeBox implements Parse internally.
https://github.com/sinclairzx81/typebox/blob/master/src/value/parse/parse.ts#L38-L68