gpt4 book ai didi

node.js - GraphQL类型解析field1列表记录,field2记录数量

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:31 25 4
gpt4 key购买 nike

我正在尝试找出如何解决这样的类型定义:

const xType = new GraphQLObjectType({
name: 'SysCountry',
description: 'SysCountry API',
fields: () => ({
states: {
type: new GraphQLList(sysCountryStateType),
resolve(sysCountry) {
const { _id } = sysCountry;
return SysCountryStateModel.find({ sysCountryId: _id }).exec();
}
},
statesQuantity: {
type: GraphQLInt,
resolve(sysCountry) {
const { _id } = sysCountry;
return SysCountryStateModel.count({ sysCountryId: _id }).exec();
}
});

其中一个字段表示记录列表,另一个字段表示记录的数量。是否有消耗更少的资源来避免查询两次或多次并从一个独特的点解决这个问题?始终返回一个简单对象(在数量的情况下为 int),而不是包含它的多个子字段的复合对象(例如同时返回字段列表和数量)。

也就是说,有没有什么方法可以解决 statesQuantity 而无需再次查询?

谢谢

最佳答案

我假设 xType 是您父级上的子级,显然您只传递 xType 上的 id 字段,您可能需要考虑的是异步获取父级上所需的数据,如果在一个请求中,它不包含子级中所需的数据,例如:

// in this child, we destructure fields we need on the root, not {id}
const GraphQLChild = new GraphQLObjectType({
name: 'Child',
fields: () => ({
id: globalIdField('News'),
userRate: {
type: new GraphQLObjectType({
name: 'userRate',
fields: {
rate: {
type: GraphQLInt,
defaultValue: 0,
resolve: ({rate}) => rate
},
important: {
type: GraphQLBoolean,
defaultValue: false,
resolve: ({important}) => important
},
saved: {
type: GraphQLBoolean,
defaultValue: false,
resolve: ({saved}) => saved
}
}
}),
resolve: ({userRate}) => userRate
},
title: {
type: GraphQLString,
resolve: ({title}) => title
},
}),
interfaces: [nodeInterface]
});

这是您想要执行异步获取的父级,如果在一个请求中,它不包含子级中所需的数据,因此解析一个包含您想要在子级上解析的所有字段的对象:

const GraphQLParent = new GraphQLObjectType({
name: 'Parent',
fields: () => ({
child: {
type: GraphQLChild,
resolve: async(root, args, context) => {
const {childId} = root;
const childData = await getChildTitle(childId).then(response => {
const {title} = response.data;
const userRate = await getChildUserRate(childId);
return new xType({userRate: {...userRate}, title});
})
},
}
})
});

在更复杂的场景中,考虑使用类构造函数,这样更容易设想要创建的对象的字段,在中继中,它用于通过 Node 定义中的实例来解析对象类型,例如:

class xType { 
constructor({
userRate,
title
}) {
this.userRate = userRate;
this.title = title;
}
}

所以所有的获取都发生在父级上,然后您只需解析子级上的字段即可。

关于node.js - GraphQL类型解析field1列表记录,field2记录数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48124085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com