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

GraphqlJS- Type conflict- Cannot use union or interface

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 函数以便能够在模式中使用联合或接口。现在,当我使用查询执行时,它向我显示错误,即我生成的模式无法使用接口或联合类型来执行。我怎样才能正确执行这个模式?

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

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