【问题标题】:Structuring the relay spec viewer in GraphQL在 GraphQL 中构建中继规范查看器
【发布时间】:2018-02-27 11:33:18
【问题描述】:

我的 Relay Schema.graphql,这是我想要实现的结构,

type Root {
  viewer: Viewer
}

type Viewer {
  categories(id: ID): Category
  subCategories(CategoryId: ID!) : [SubCategory]
  items(SubCategoryId: ID): Item
  shopItems(ShopId: ID, SubCategoryId:ID): Item
}

现在服务器,我的 viewer.js 看起来像这样,

const Viewer = new GraphQLObjectType({
  name: 'viewer',
  fields: {
    categories,
    subCategories,
    Items,
    shopItems,
  },
});

根是,

const RootQuery = new GraphQLObjectType({
  name: 'query',
  fields: {
    viewer: {
      type: Viewer,
    },
  },
});

它给了我想要的结构,但我无法从 rootQuery 解析任何内容,查看器只是返回 null,因为我没有解析 rootQuery 中的查看器类型。任何想法如何正确实施此中继规范结构?谢谢大家

【问题讨论】:

    标签: graphql relayjs graphql-js


    【解决方案1】:

    如果没有显示解析器的代码(也许您使用的是默认代码),这应该会有所帮助。

    您正在使用具有根viewer 对象的公认模式,其“类型”是真正的根查询类型。该类型需要为其字段提供一种解决您真实架构的方法。例如:

    const subCategories = {
      type: GraphQLList({ ofType: SubCategory }),
      arguments: {
        CategoryId: { type: GraphQLNonNull({ ofType: GraphQLID }),
      },
      resolve(rootValue, { CategoryId }, context, info) {
        // look stuff up based on CategoryId and return it
      },
    };
    
    const Viewer = new GraphQLObjectType({
      name: 'viewer',
      fields: {
        categories,
        subCategories,
        Items,
        shopItems,
      },
    });
    

    【讨论】:

    • 嗯,我已经做到了。这些字段已经定义并且我正在导入它们。
    • Grapqhl 希望我解析根查询中的查看器字段。我显然做不到。
    • 当然可以,只需将您自己的解析器函数提供给graphql?
    • 我将不得不解析具有已解析字段类别、子类别等的查看器类型。如果我不解析查看器,则查询返回 null,因为它希望解析查看器。
    • 你试过这里给出的模式吗? graphql.org/graphql-js/object-typesViewer 的各个字段将具有上述解析器函数,它将返回适当创建的 JS 对象。
    【解决方案2】:

    愚蠢的我,通过像这样解析查看器来解决它,

    const RootQuery = new GraphQLObjectType({
      name: 'query',
      fields: {
        viewer: {
          type: Viewer,
          resolve(viewer, args) {
           return {viewer: viewer}
         }
        },
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2011-01-27
      • 1970-01-01
      相关资源
      最近更新 更多