2

我正在尝试将我的 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);

我尝试使用两个包 class-transformer 和 class-validator 来转换和验证 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-schema。

欢迎任何建议。

4

2 回答 2

1

我从来没有这样做过,但你可以用另一种方式来做。

使用typed-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();

免责声明:我是typed-ajv的维护者之一

于 2021-11-11T16:48:41.290 回答
1

我使用了一个名为class-validator-jsonschema的库,它帮助我根据需要将类转换为 json-schema。

这是代码:

import { IsNumber, IsString } from 'class-validator';

export class TodoDTO {
    @IsNumber()
    id?: number;

    @IsString()
    name?: string;

    @IsString()
    description?: string;
}
import { validationMetadatasToSchemas } from 'class-validator-jsonschema';
import * as todoDtos from './todo.dto';

export { todoDtos };

export const schemas = validationMetadatasToSchemas();

console.log('schemas=>', schemas);
于 2021-11-13T10:24:27.507 回答