samedi 3 avril 2021

convert a typeorm Entity into json schema

I'm working on a fastify rest server implementation in JS and I want to use the same typeorm entity as the json schema for the rest API which will allow validation and swagger documentation.

An entity example might be:

import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
class Location {
    @PrimaryGeneratedColumn()
    id = undefined;

    @Column({ type: 'varchar', length: 100 })
    name = '';

    @Column({ type: 'varchar', length: 255 })
    description = '';
}

export default Location;

The route itself:

fastify.get('/', { schema }, async () => (
  // get all Locations from the database
));

For the schema object (passed as the second argument to fastify route), I need to pass a json schema describing the body and/or return value (in this case, the return value) The schema should look something like:

{
  schema: {
    response: {
      200: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            id: { type: 'string', primary: true, generated: true },
            name: { type: 'string', maxLength: 100 },
            description: { type: 'string', maxLength: 255 }
          }
        }
      }
    }
  }
}

Bottom line, I want to convert the Entity above to this schema. Is there a method in Typeorm that converts the class into a json structure or do I need to somehow reflect on the class.

How do I do that?





Aucun commentaire:

Enregistrer un commentaire