GraphqlJS-类型冲突 - 不能使用联合或接口
const { makeExecutableSchema
} = require('graphql-tools');
const resolvers = require('./resolvers');
const typeDefs = `
type Link {
args: [Custom]
}
union Custom = One | Two
type One {
first: String
second: String
}
type Two {
first: String
second: [String]
}
type Query {
allLinks: [Link]!
}
`;
const ResolverMap = {
Query: {
__resolveType(Object, info) {
console.log(Object);
if (Object.ofType === 'One') {
return 'One'
}
if (Object.ofType === 'Two') {
return 'Two'
}
return null;
}
},
};
// Generate the schema object from your types definition.
module.exports = makeExecutableSchema({
typeDefs,
resolvers,
ResolverMap
});
//~~~~~resolver.js
const links = [
{
"args": [
{
"first": "description",
"second": "<p>Some description here</p>"
},
{
"first": "category_id",
"second": [
"2",
"3",
]
}
]
}
];
module.exports = {
Query: {
//set data to Query
allLinks:() => links,
},
};
我很困惑,因为graphql的纪录片太糟糕了。我不知道如何设置resolveMap函数以便能够在模式中使用union或interface。现在,当我使用查询执行时,它显示我生成的模式不能使用Interface或Union类型执行的错误。我该如何正确执行这个模式?GraphqlJS-类型冲突 - 不能使用联合或接口
回答:
resolvers
和ResolverMap
应该一起定义为resolvers
。另外,应该为Custom
联合类型定义类型解析器,而不是Query
。
const resolvers = { Query: {
//set data to Query
allLinks:() => links,
},
Custom: {
__resolveType(Object, info) {
console.log(Object);
if (Object.ofType === 'One') {
return 'One'
}
if (Object.ofType === 'Two') {
return 'Two'
}
return null;
}
},
};
// Generate the schema object from your types definition.
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
更新: OP得到了一个错误"Abstract type Custom must resolve to an Object type at runtime for field Link.args with value \"[object Object]\", received \"null\"."
。这是因为解析器Object.ofType === 'One'
和Object.ofType === 'Two'
中的条件始终是错误的,因为在Object
内没有称为ofType
的字段。所以解决的类型总是null
。
为了解决这个问题,无论是ofType
场args
阵列(在resolvers.js
links
常数)添加到每个项目或变更的条件类似typeof Object.second === 'string'
和Array.isArray(Object.second)
以上是 GraphqlJS-类型冲突 - 不能使用联合或接口 的全部内容, 来源链接: utcz.com/qa/265003.html