首先设置上下文。我有一个graphql服务器运行,我用它来查询服务器启动时实例化的对象之一(内存数据库的种类)。每次加载模式时都会创建公司对象,或者说我正在使用QueryType对象来解析服务器。
这是graphQL Schema
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLList
} = require('graphql');
const {
connectionDefinitions,
connectionArgs,
connectionFromArray,
connectionFromPromisedArray
} = require('graphql-relay');
//**************************** In-Memory Data ********************************//
var company = {
id:'123456',
customFieldDefinitions:[
{
name: 'cfm1',
id: '123'
},
{
name: 'cfm2',
id: '1234'
}
]
};
//**************************** In-Memory Code Ends *********************************//
const CustomFieldDefinitionType = new GraphQLObjectType({
name: 'Common_CustomFieldDefinitionsConnection',
fields: {
id: {
type: GraphQLString,
resolve: (cfd) => cfd.id
},
name: {
type: GraphQLString,
resolve: (cfd) => cfd.name
}
}
});
const { connectionType: CustomFieldDefinitionConnection } =
connectionDefinitions({
name: 'Common_CustomFieldDefinition',
nodeType: CustomFieldDefinitionType
});
const CompanyType = new GraphQLObjectType({
name: 'Company',
fields: {
id: {
type: GraphQLString,
resolve: (obj) => obj.id
},
customFieldDefinitions: {
type: CustomFieldDefinitionConnection,
description: 'A list of Custom Fields',
args: connectionArgs,
resolve: (obj, args) => connectionFromPromisedArray(obj.customFieldDefinitions, args)
}
}
});
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: {
company: {
args: {
id: { type: GraphQLString },
},
type: CompanyType,
resolve: (_, args) => company
}
}
});
const mySchema = new GraphQLSchema({
query: QueryType
});
module.exports = mySchema;
现在我尝试在graphiQL编辑器上查询如下
query{
company{
customFieldDefinitions {
edges {
node {
id
}
}
}
}
}
我收到如下错误。
{
"data": {
"company": {
"customFieldDefinitions": null
}
},
"errors": [
{
"message": "dataPromise.then is not a function",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"company",
"customFieldDefinitions"
]
}
]
}
有人可以帮我识别问题。
答案 0 :(得分:2)
看起来错误在于这一行:
resolve: (obj, args) => connectionFromPromisedArray(obj.customFieldDefinitions, args)
问题是从connectionFromPromisedArray
导入的graphql-relay
函数需要一个返回数组的promise,而obj.customFieldDefinitions
是一个普通数组。只是为了追溯它,obj
是该解析器的父元素,在这种情况下,您从company
类型的Query
解析器返回的内容。
要解决此问题,请将connectionFromPromisedArray
更改为connectionFromArray
或将公司对象更改为:
var company = {
id:'123456',
customFieldDefinitions: Promise.resolve([
{
name: 'cfm1',
id: '123'
},
{
name: 'cfm2',
id: '1234'
}
])
};