将 typeorm 实体转换为 json 模式

问题描述

我正在 JS 中进行 fastify rest 服务器实现,我想使用与 json 模式相同的 typeorm 实体作为 rest API,这将允许验证和 swagger 文档。

实体示例可能是:

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;

路线本身:

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

对于 schema 对象(作为第二个参数传递给 fastify 路由),我需要传递一个描述主体和/或返回值(在本例中为返回值)的 json 模式 架构应该类似于:

{
  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 }
          }
        }
      }
    }
  }
}

最重要的是,我想将上面的实体转换为这个模式。 Typeorm 中是否有将类转换为 json 结构的方法,或者我是否需要以某种方式反映该类。

我该怎么做?

解决方法

似乎解决方案非常简单 - connection.getMetadata(Location) 提供了有关表格的大量信息。我只需要将该数据转换为我期望的 json 模式。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...