将typeorm实体转换为json模式



我正在JS中研究一个fastify rest服务器实现,我想为rest API使用与json模式相同的typeorm实体,这将允许验证和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 route的第二个参数传递(,我需要传递一个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模式。

我也遇到了同样的问题,环顾四周,我发现了一个名为typeorm schema到json schema的小npm模块,它是为此目的创建的,认为它需要将实体类定义为EntitySchemas。

最新更新