GraphqlJS-类型冲突 - 不能使用union或接口

时间:2017-12-27 12:19:34

标签: javascript graphql graphql-js

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类型执行。如何正确执行此架构?

1 个答案:

答案 0 :(得分:2)

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'中的条件始终为false,因为ofType内没有名为Object的字段。因此,已解析的类型始终为null

要解决此问题,请为ofType数组中的每个项目添加args字段(links中的resolvers.js常量)或将条件更改为typeof Object.second === 'string' }和Array.isArray(Object.second)