[英]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.