2017-12-27 210 views
0
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-类型冲突 - 不能使用联合或接口

回答

1

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)

+0

林现在收到错误:“'抽象类型的自定义必须解析运行时的对象类型,其值为字段Link.args,值为“[object Object] \”,收到“null”。“我必须定义'type Custom'吗?它应该包含什么? – Brunhilda

+1

我认为这是因为Object.ofType ==='One''和Object.ofType ==='Two''总是'false'。所以解析的类型总是为null。尝试在'args'数组中的每个项目中添加'ofType'字段('resolvers.js'中的'links'常量)。或者将条件改为'typeof Object.second ==='string''和'Array.isArray(Object.second)'。我无法验证,因为我现在不在我的电脑。 – Bless

+0

哦,我的上帝,你,我爱你。我已经考虑了好几个星期了,一群人试图帮助我,而且过了很长一段时间,终于有了一个答案。你是我的救星。你现在不知道我有多幸福。 – Brunhilda