javascript - GraphqlJS-类型冲突-无法使用联合或接口(interface)

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

最佳答案

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)

关于javascript - GraphqlJS-类型冲突-无法使用联合或接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47992095/

相关文章:

javascript - 使用 D3 将 SVG 文本元素 id 与数据 id 进行匹配

javascript - Angular 服务不能作为单例工作

reactjs - WebSocket 连接到 'ws:<URL>/_next/webpack-hmr' 失败 : WebSocket is closed before the connection is established

javascript - 如何使用 Apollo 在 Vue 中实现有效的 Graphql 查询?

javascript - 如何访问父查询值来构造新查询?

javascript - 在多维数据集的 SQL 定义中使用上下文变量时,Cube.js 是否支持预聚合?

javascript - 从 promise 回调更改 vue 数据

python - 具有外键关系的对象的 Graphite 烯中的 GraphQL 突变

graphql - 优化 graphql 数据库查询

javascript - 创建多变量 GraphQL 查询