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类型执行。如何正确执行此架构?
答案 0 :(得分:2)
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'
中的条件始终为false,因为ofType
内没有名为Object
的字段。因此,已解析的类型始终为null
。
要解决此问题,请为ofType
数组中的每个项目添加args
字段(links
中的resolvers.js
常量)或将条件更改为typeof Object.second === 'string'
}和Array.isArray(Object.second)