我正在用JS开发一个fastify rest服务器实现,我想使用相同的typeorm实体作为rest API的json模式,这将允许验证和夸张文档。
实体示例可能是:
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结构,或者我是否需要以某种方式反映这个类。
我该怎么做?
发布于 2021-04-05 15:01:04
看起来解决方案非常简单-- connection.getMetadata(Location)
提供了很多关于表的信息。我只需将该数据转换为我所期望的json模式。
发布于 2021-08-16 19:56:31
我遇到了同样的问题,环顾四周,我发现了一个名为typeorm-schema-to-json-schema的小npm模块,它是为此目的而创建的,认为它需要defining entity classes as EntitySchemas。
https://stackoverflow.com/questions/66931653
复制相似问题