【问题标题】:Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?将 TypeORM 实体模型类与 NestJS-GraphQL 模式类型结合使用好吗?
【发布时间】:2023-04-06 23:53:01
【问题描述】:

我正在使用NestJSTypeORM 创建一个GraphQL API。从经典的用户实体开始,我按照 Nestjs 文档的描述创建了 user.type.tsuser.entity.ts

这是内容示例:

  • user.entity.ts
@Entity({ schema: 'mydb', name: 'userList' })
export class User {

    @Column('varchar', { name: 'guid', unique: true, length: 36 })
    guid: string;

    @Column('varchar', { name: 'firstName', length: 50 })
    firstName: string;

    @Column('varchar', { name: 'lastName', length: 100 })
    lastName: string;

    // ...
  • user.type.ts
@ObjectType()
export class UserType {
  @Field({
    name: 'ID',
    description: 'Global Universal ID of the User',
  })
  guid: string;

  @Field()
  firstName: string;

  @Field()
  lastName: string;

  // ...

问题是:由于它们使用相同的字段,我可以创建一个将两个类的装饰器组合在一起的类吗?

例如:

@Entity({ schema: 'mydb', name: 'userList' })
@ObjectType()
export class User {

    @Column('varchar', { name: 'guid', unique: true, length: 36 })
    @Field({
      name: 'ID',
      description: 'Global Universal ID of the User',
    })
    guid: string;

    @Field()
    @Column('varchar', { name: 'firstName', length: 50 })
    firstName: string;

    @Field()
    @Column('varchar', { name: 'lastName', length: 100 })
    lastName: string;

它是反模式吗?这样做有什么限制或缺点吗?

提前致谢

【问题讨论】:

    标签: typescript graphql nestjs dry typeorm


    【解决方案1】:

    你可以按照你的建议去做。这不是问题。这样做是个人喜好。

    但是,您可能会像我一样很快了解到,尽管从数据结构的角度来看,两者具有相同的形状,但实体和 GraphQL 对象(或在 NestJS 术语中,数据传输对象或 DTO)确实有不同目的。您还会发现在某些情况下需要从一种转换为另一种,而这样做需要将它们分开。

    【讨论】:

    • 嗨!感谢您的回复!
    • 我一直在使用带有 REST 的 DTO,但在 graphql 中我认为它们没用,因为字段映射和验证是由 graphql 完成的。此外,对于查询/突变的参数,我使用了一个单独的类。我上面提到的混合类将仅用于 gql 有效负载,我可以使用 graphl 装饰器轻松隐藏/转换/扩展字段。现在我真的不明白让他们分开的意义。你能给我一个真实的例子吗?
    • @Joseph - 我可以举出的一个很好的例子是,当您的 API 字段名称应该与数据库的字段名称不同时。如果您一起构建实体和 GraphQL 对象,您会遇到 api 名称和实体字段名称必须相同的问题。可能看起来不是问题,但可能是。
    • 谢谢!是的,我的想法相同,但实际上使用 Nestjs 上的 @Field 装饰器,您可以定义字段名称的映射。例如:@Field({name: ID}) guid: string; 这意味着您的 db 字段被称为 guid,但它被公开为 ID。你也可以@HideField 和类似的东西。目前我没有看到限制,但我也会尝试发现它们
    猜你喜欢
    • 2011-10-04
    • 2021-02-20
    • 1970-01-01
    • 2012-05-19
    • 2015-08-08
    • 2020-03-07
    • 2021-11-03
    • 2020-11-15
    • 2019-02-07
    相关资源
    最近更新 更多