我正在尝试将我的DTO类(Typescript(转换为JSON模式:
import { IsNumber, IsString } from 'class-validator';
import { classToPlain } from 'class-transformer';
export class TodoDTO {
@IsNumber()
id?: number;
@IsString()
name?: string;
@IsString()
description?: string;
}
let todo = classToPlain(TodoDTO);
console.log('todo=>', todo);
我尝试使用两个包类转换器和类验证器来转换和验证TodoDTO类。
在控制台中,它以todo=> [Function: TodoDTO]
的形式输出
预期输出:
"TodoDTO": {
"type": "object",
"properties": {
"id": { "type": "number" },
"name": { "type": "string" },
"description": { "type": "string" }
},
"required": [ "id", "name", "description" ]
}
我正在尝试使用TodoDTO类作为fastify typescript中的json模式。
欢迎提出任何建议。
我使用了一个名为类验证器jsonschema的库,它帮助我根据需要将类转换为json模式。
这是代码:
import { IsNumber, IsString } from 'class-validator';
export class TodoDTO {
@IsNumber()
id?: number;
@IsString()
name?: string;
@IsString()
description?: string;
}
我从来没有用过这种方式,但你可以用另一种方式来执行。
使用类型化的ajv,您可以将类似ajv的dsl转换为ts类和json模式。
示例
import { CS } from '@keplr/typed-ajv'; const TodoDTOCS = CS.Object({ id: CS.Number(true), name: CS.String(false), description: CS.String(false), }); type TodoDTO = typeof TodoDTOCS.type; // TodoDTO is the correct ts type const todo: TodoDTO = { // } // jsonSchema will be the expected json-schema format const jsonSchema = TodoDTOCS.getJsonSchema();
免责声明:我是类型的ajv的维护者之一