graphql - NestJS + Typeorm + Graphql : correct design pattern for DTO in nested relations

标签 graphql nestjs typeorm

假设我有一个像这样的 Typeorm 实体定义:

@Entity()
export class MyEntity {
  @PrimaryGeneratedColumn()
  id: number;

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

  ...

  @OneToOne(type => DocumentEntity)
  @JoinColumn()
  myDoc: DocumentEntity;

  @OneToMany(type => DocumentEntity, document => document.myEntity)
  @JoinColumn()
  otherDocs: DocumentEntity[];

  ...
}

所以它有几个实体关系,OneToMany/OneToOne

在制作 DTO 时如何解决这个问题?

这里有一个 DTO 示例:

export class CreateMyEntityInputDto {

  @IsString()
  name: string;

  ...

  @IsOptional()
  myDoc: DocumentEntity;

  @IsOptional()
  otherDocs: DocumentEntity[];

  ....
}

我不清楚通过 Graphql 的最佳方法

当前的graphql接口(interface):

####################
# @input
####################
input CreateDealInput {
  name: String
  ...
  myDoc: DocumentInput
  otherDocs: [DocumentInput]
} 

如果我设计“传统”RESTful 服务,我将通过单独的端点在数据库中创建文档,等待返回 documentID(s):int 的成功

然后在 myEntity.myDoc/myEntity.otherDocs 中将这些 ID 指定为纯整数 创建新的 myEntity 时的字段(在单独的端点)。

我在这里采取同样的方法吗? 我是否在 graphql 中的单独查询中创建文档实体,从成功响应中解析出创建的 id,然后在 DTO 定义中指定这些 int 值?

类似于:

@IsOptional()
myDoc: int;

然后,在创建 myEntity 时,通过 id:int 加载那些(现有的)文档实体,然后最终通过 Typeorm 保存?

或者我是否将所有文档字段作为嵌套实体传递到一个大型嵌套 POST graphql 查询中,并使用级联来创建它们?

最佳答案

我自己也遇到了同样的问题。我的解决方案是通过 id 引用嵌套实体。在您的示例中,这将类似于:

export class CreateMyEntityInputDto {

  @IsString()
  name: string;

  ...

  @IsOptional()
  myDocId: string;

  @IsOptional()
  otherDocIds: string[];

  ....
}

该解决方案需要多个实体,而不是在一个突变中创建嵌套实体。

关于graphql - NestJS + Typeorm + Graphql : correct design pattern for DTO in nested relations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487415/

相关文章:

typescript - 为 NestJs REST API 创建 DTO、BO 和 DAO

javascript - 将多个 const = 组合在一个数组中?

node.js - graphql 解析器中的授权作为中间件

javascript - 如何正确处理异步错误?

mysql - 如何在 typeorm 和 Nest.js 中设置 bool 验证

nestjs - 我可以将实体字段名称映射到 typeorm 中的别名列名称吗?

typescript - TypeORM ColumnTypeUndefined 错误排查步骤?

javascript - 如何在 Apollo 中关闭 GraphQL 订阅的套接字连接

graphql - Nestjs/GraphQL - Playground 返回查询的空错误。我的解析器?

jestjs - 无法模拟 createQueryBuilder 函数 typeorm Nestjs Jest