graphql - GraphQL 端点在 Nest.js 中返回空对象
问题描述
我正在使用 Nest.js 和 Sequelize-Typescript 构建 GraphQL API。
当我调用删除和更新突变时,我得到了一个空对象,但操作完成了。我需要输入 {nullable: true} 因为我得到一个错误说Cannot return null for non-nullable field
。我该如何解决?我需要端点返回更新的对象以在前面显示信息
书本.dto.ts
import { ObjectType, Field, Int, ID } from 'type-graphql';
@ObjectType()
export class BookType {
@Field(() => ID, {nullable: true})
readonly id: number;
@Field({nullable: true})
readonly title: string;
@Field({nullable: true})
readonly author: string;
}
book.resolver.ts
import {Args, Mutation, Query, Resolver} from '@nestjs/graphql';
import { Book } from './model/book.entity';
import { BookType } from './dto/book.dto';
import { CreateBookInput } from './input/createBook.input';
import { UpdateBookInput } from './input/updateBook.input';
import { BookService } from './book.service';
@Resolver('Book')
export class BookResolver {
constructor(private readonly bookService: BookService) {}
@Query(() => [BookType])
async getAll(): Promise<BookType[]> {
return await this.bookService.findAll();
}
@Query(() => BookType)
async getOne(@Args('id') id: number) {
return await this.bookService.find(id);
}
@Mutation(() => BookType)
async createItem(@Args('input') input: CreateBookInput): Promise<Book> {
const book = new Book();
book.author = input.author;
book.title = input.title;
return await this.bookService.create(book);
}
@Mutation(() => BookType)
async updateItem(
@Args('input') input: UpdateBookInput): Promise<[number, Book[]]> {
return await this.bookService.update(input);
}
@Mutation(() => BookType)
async deleteItem(@Args('id') id: number) {
return await this.bookService.delete(id);
}
@Query(() => String)
async hello() {
return 'hello';
}
}
book.service.ts
import {Inject, Injectable} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {Book} from './model/book.entity';
import {DeleteResult, InsertResult, Repository, UpdateResult} from 'typeorm';
@Injectable()
export class BookService {
constructor(@Inject('BOOKS_REPOSITORY') private readonly bookRepository: typeof Book) {}
findAll(): Promise<Book[]> {
return this.bookRepository.findAll<Book>();
}
find(id): Promise<Book> {
return this.bookRepository.findOne({where: {id}});
}
create(data): Promise<Book> {
return data.save();
}
update(data): Promise<[number, Book[]]> {
return this.bookRepository.update<Book>(data, { where: {id: data.id} });
}
delete(id): Promise<number> {
return this.bookRepository.destroy({where: {id}});
}
}
解决方案
您可以在解析器查询中修复它设置选项参数
@Query(() => BookType, { nullable: true })
推荐阅读
- javascript - Javascript 过滤器方法返回原始数组,即使返回 false
- c# - Print name and id of radio button?
- r - 如何在 R 传单中将 SP 对象绘制为 SF
- flask - 为什么我的表单数据没有添加到 flask-sqlalchemy 和 jinja 模板中的数据库中?
- system-verilog - 一个实例静态类型强制转换形式子类如何使用变量和函数?
- javascript - 如何将多个列表合并为一个列表?
- vba - 使用 VBA 将 MS Access 报告转换为 PDF 时,字符上出现间歇性框
- spring-boot - 为什么 Kafka Producer 在 Spring Boot 中发布带有双引号的字符串消息
- swift - 在模型中创建枚举
- c# - 使用 Xunit 运行单元测试