Convert Typescript Class DTO into JSON Schema for Fastify Swagger

Viewed 1523

I am trying to convert my DTO class (Typescript) to JSON schema:

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);

I tried to use two packages class-transformer and class-validator to transform and validate TodoDTO class.

In console it gives output as todo=> [Function: TodoDTO]

Expected output:

"TodoDTO": {
   "type": "object",
   "properties": {
       "id": { "type": "number" },
       "name": { "type": "string" },
       "description": { "type": "string" }
    },
   "required": [ "id", "name", "description" ]
}

I am trying to use TodoDTO class as a json-schema in fastify-typescript.

Any suggestions are welcome.

2 Answers

I never did it in this way, but you can perform it in the other way.

Using typed-ajv you can convert a ajv-like dsl to ts classes and json schema.

Example

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();

Disclaimer : I was one of the maintainer of typed-ajv

I used a library called class-validator-jsonschema which helped me to convert the class to json-schema as required.

Here is the code :

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);
Related