[type] Convert to JSON schema
Hi there!
Are there already plans for being able to convert a validator into a JSON schema similar to how class-validator does it? I really like the speed improvement, but being able to use the same validation across my whole stack is actually quite an important feature for me. If you have ideas, how to do this, but don't have it on the roadmap yet, I would also be happy to just get some pointers and could try creating a package for this myself :)
Wasn't planned yet, but seems like a reasonable addition. We have already all the schema information normalized in a ClassSchema, so a JSON-Schema generator should not take that much time.
Kinda like this:
class User {
@t created: Date = new Date;
@t.optional birthDate?: Date;
constructor(@t public username: string) {
}
}
const schema = getClassSchema(User);
const jsonSchemaEntity: any = {
description: schema.description,
properties: [],
required: [],
type: 'object',
}
for (const property of schema.getClassProperties()) {
const jsonProperty: any = {
type: property.type, //needs mapping for certain types, e.g. 'class'
}
if (!property.isOptional() jsonSchemaEntity.required.push(property.name);
if (property.type === 'array') {
//recursive call required when subType is 'array' again or 'class'
const subType = property.getSubType();
property.items = {
type: subType.type,
//etc.
}
}
//todo: handle property.validators, e.g. maxLength etc
jsonSchemaEntity.properties[property.name] = jsonProperty;
}
const jsonSchema: any = {
[schema.name || schema.getClassName()]: jsonSchemaEntity
};
That just as example how the API works. This needs to be written of course in a way that handles recursive embedded documents/arrays, etc.
Thanks! Ideally, the type mapping would be colocated to the validator definitions I think. But nice that the code structure is already in place :)
the type mapping would be colocated to the validator definitions
JSON-Schema is one validation framework. Adding knowledge about that domain to the validators itself, would lock that framework. However, I think it's better to decouple this information and let the JSON-Schema generator know about validators and how to treat them instead of vice-versa.
Ok. Then we should make sure that there are tests in place which make sure that each validator has a corresponding JSON schema generator and that they do the same thing, as otherwise, they might diverge (the dark side of decoupling ;) ). And this could cause big trouble if validation across a system is not consistent.
https://github.com/hanayashiki/deepkit-openapi can create json schema files from TS types.