[英]possible to count result list elements in type-graphql
我是 typeGraphQL 的新手,我的问题是可能对结果列表元素进行计数
我有模型类型的书
import { Field, ID, ObjectType, Root } from "type-graphql";
import { Model, Column } from "sequelize-typescript";
@ObjectType()
export default class Books extends Model<Books>
{
@Field(() => ID)
@Column
id: number;
@Field(() => String)
@Column
bookName: string;
}
在解析器中查询
@Query(() => [Books])
async getBooks()
{
return Books.findAll()
}
在 graphiQL 中运行查询时
getTest
{
id
bookName
}
得到回应
"getBooks" :
[
{
"id": "1",
"bookName": "bookOne"
},
{
"id": "2",
"bookName": "bookTwo"
}
]
但我需要添加附加字段,例如获取所有收到项目的总计数。 如何正确地做到这一点? 现在我们必须创建一个单独的查询,但是对于大样本来说,这是非常不方便的,并且会导致重复复杂和大的查询
@Query(() => [Books])
async countBooks()
{
return Books.findAll().length
}
我尝试为元素数量和模型本身创建一个单独的联合类型
@ObjectType()
export default class UnionType extends Model<UnionType>
{
@Field(() => [Books])
books: Books[];
@Field(() => Int)
totalCount(@Root() parent : UnionType) : number
{
return parent.books.length;
}
}
并在解析器中运行下一个查询
@Query(() => [UnionType])
async getBooksAndCountAll()
{
let union : any = {}
union.books = Books.findAll();
union.totalCount = union.books.length;
return union;
}
但是在运行查询error "message": "Expected Iterable, but did not find one for field Query.getBooks.",
据我所知,它没有传输模型期望的数据
我尝试使用 createUnionType
import { createUnionType } from "type-graphql";
const SearchResultUnion = createUnionType({
name: "Books", // the name of the GraphQL union
types: [Books, CountType], // array of object types classes
});
其中 UnionType
@ObjectType()
export default class CountType extends Model<CountType>
{
@Field(() => Int, { nullable : true })
totalCount: number;
}
在解析器中查询
@Query(returns => [SearchResultUnion])
async getBooks(
): Promise<Array<typeof SearchResultUnion>>{
return new Promise((resolve, reject) => {
Books.findAll()
.then(books => {
let totalCount = books.length;
return [...books, ...totalCount];
});
});
}
但是在字符串return [...books, ...totalCount];
на ...totalCount
Type 'number' must have a '[Symbol.iterator]()' method that returns an iterator.
如果你不通过...totalCount
请求有效,但是没有分别已经没有totalCount
getTest{
__typename
... on Books
{
id
bookName
}
}
要求
"getBooks": [
{
"id": "1",
"bookName": "bookOne"
},
{
"id": "2",
"bookName": "bookTwo"
}
]
所以,结果我需要一个请求
getTest
{
totalCount
__typename
... on Books{
id
bookName
}
}
可能吗?
来自https://github.com/19majkel94/的答案
谢谢,迈克尔·莱泰克
@ObjectType()
export default class GetBooksResponse {
@Field(() => [Books])
books: Books[];
@Field(() => Int)
totalCount : number;
}
@Query(() => GetBooksResponse)
async getBooks() {
const books = await Books.findAll();
return { books, totalCount: books.length };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.