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函数以便能够在模式中使用联合或接口(interface)。现在,当我使用查询执行时,它会显示错误,表明我生成的架构无法使用接口(interface)或联合类型来执行。我怎样才能正确执行这个模式?
最佳答案
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)
关于javascript - GraphqlJS-类型冲突-无法使用联合或接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47992095/