【问题标题】:convert a typeorm Entity into json schema将 typeorm 实体转换为 json 模式
【发布时间】:2021-04-03 13:23:58
【问题描述】:

我正在用 JS 开发一个 fastify REST 服务器实现,我想使用与 json 架构相同的 typeorm 实体作为其余 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 结构的方法,还是我需要以某种方式反映类。

我该怎么做?

【问题讨论】:

    标签: reflection jsonschema typeorm fastify


    【解决方案1】:

    看来解决方案非常简单——connection.getMetadata(Location) 提供了很多关于表格的信息。我只需要将该数据转换为我期望的 json 模式。

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,环顾四周,我发现为此目的创建了一个名为 typeorm-schema-to-json-schema 的小型 npm 模块,我认为它需要 defining entity classes as EntitySchemas

      【讨论】:

        猜你喜欢
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 2016-09-09
        • 2017-03-27
        • 2013-10-14
        • 2016-06-18
        相关资源
        最近更新 更多