【问题标题】:Type '[]' is missing the following properties from type ''" graphql类型“[]”缺少类型“”中的以下属性 graphql
【发布时间】:2021-01-08 18:01:27
【问题描述】:

我在 typeGraphQL 中有一个简单的解析器,它 findOne 并针对查询返回一条记录,我对 Company 模型有类似的实现工作得很好,但 产品 不起作用,让我给你看我的代码

entity/Product.ts

import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";
import { ObjectType, Field, ID } from "type-graphql";

//the field decorator represents which fields user can query

@ObjectType()
@Entity()
export class Product extends BaseEntity {
  @Field(() => ID)
  @PrimaryGeneratedColumn() 
  id: number;

  @Field({nullable: true})
  @Column({length: 300, nullable: true})
  description: string;

  @Field({nullable: true})
  @Column({length: 300, nullable: true})
  image: string;

  @Field({nullable: true})
  @Column({ length: 300, nullable: true })
  stock: string;

  @Field({nullable: true})
  @Column({ length: 300, nullable: true })
  color: string;

  @Field()
  @Column({length: 300})
  name: string;

  @Field()
  @Column({length: 300})
  company_id: string;
}

解析器

import { Resolver, Query,Arg } from "type-graphql";
import { Product } from "../../entity/Product";


@Resolver()
export class ProductResolver {

  @Query(() => Product)
  async companyProducts(
    @Arg("name") company_id: string,
  ): Promise<Product | null> {
    const product=await Product.findOne({ where: { company_id } });
    console.log(product)
    return product;
    // return product;
  }
}

console.log() 确实打印出预期的对象,但是当我返回时,我得到了

Type 'Product | undefined' is not assignable to type 'Product | null'.

知道可能是什么原因吗?

【问题讨论】:

  • 在解析器中将返回类型从 Promise&lt;Product | null&gt; 更改为 Promise&lt;Product | undefined&gt;
  • 很好,但是!如果没有返回记录,我得到“不能为不可为空的字段 Query.companyProducts 返回 null”
  • 这是因为您正在使用此装饰器@Query(() =&gt; Product) 这表明将返回“产品”,我对 type-graphql 的经验有限,但您可以尝试将所有字段设置为空,因为(基于我的假设)namecompany_id 字段不可为空。
  • 此外,如果上述解决方案不起作用,则可能值得将查询装饰器从 @Query(() =&gt; Product) 更改为 @Query(() =&gt; Product | null),然后将 return product; 更改为 return product || null;
  • 很遗憾,两者都不起作用!

标签: node.js typeorm typegraphql


【解决方案1】:
  1. 通过@Query(() =&gt; Product, { nullable: true }) 使您的查询可以为空。

  2. 将您的查询方法返回类型签名更改为 Promise&lt;Product | undefined&gt; 或在未定义产品时返回 null。

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 2021-07-29
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2020-05-23
    • 2020-04-09
    相关资源
    最近更新 更多