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-类型冲突 - 不能使用联合或接口

回答:

resolversResolverMap应该一起定义为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

为了解决这个问题,无论是ofTypeargs阵列(在resolvers.jslinks常数)添加到每个项目或变更的条件类似typeof Object.second === 'string'Array.isArray(Object.second)

以上是 GraphqlJS-类型冲突 - 不能使用联合或接口 的全部内容, 来源链接: utcz.com/qa/265003.html

回到顶部