【发布时间】: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<Product | null>更改为Promise<Product | undefined>。 -
很好,但是!如果没有返回记录,我得到“不能为不可为空的字段 Query.companyProducts 返回 null”
-
这是因为您正在使用此装饰器
@Query(() => Product)这表明将返回“产品”,我对 type-graphql 的经验有限,但您可以尝试将所有字段设置为空,因为(基于我的假设)name和company_id字段不可为空。 -
此外,如果上述解决方案不起作用,则可能值得将查询装饰器从
@Query(() => Product)更改为@Query(() => Product | null),然后将return product;更改为return product || null; -
很遗憾,两者都不起作用!
标签: node.js typeorm typegraphql