繁体   English   中英

GraphQL解析器问题

[英]GraphQL Resolver Problems

我已经花了很多时间阅读GraphQL教程,但是不幸的是,它们似乎没有足够深入地介绍我。 我非常感谢这个实际示例的帮助。

在示例中,查询位于解析器对象的根目录下。 我可以使它在单级查询中正常工作。 当我尝试解析嵌套查询时,嵌套解析器永远不会被调用。 我大为困惑的是,我发现没有在graphql网站上发布的每个教程都放在Query对象中,并将其查询嵌套在根目录下,而不是根目录下。

考虑以下架构:

type Product {
  id: String!
  retailerId: String!
  title: String!
  description: String
  price: String!
  currency: String!
}

type OrderLine {
  product: Product!
  quantity: Int!
}

type Order {
  id: String!
  retailerId: String!
  orderDate: Date!
  orderLines: [OrderLine!]!
}

type Query {
  product(id: String!): Product
  order(id: String!): Order
}

schema {
    query: Query
}

和以下查询:

query {
    order(id: "1") {
        id
        orderLines {
            quantity
        }
    }
}

我已经尝试实现解析器的多个版本(现在仅测试数据),但似乎没有一个返回我所讲的内容。 这是我当前的解析器实现:

const resolvers = {
  OrderLine: {
    quantity: () => 1,
  },
  Order: {
    orderLines: (parent: any, args: any) => { console.log("Calling order lines"); return []; },
  },
  Query: {
    product(parent, args, ctx, other) {
      return { id: args.id.toString(), test: true };
    },
    order: ({ id }) => { console.log("Calling order 1"); return { id: id.toString(), testOrder: true, orderLines: [] }; },
  },
  order: ({ id }) => { console.log("Calling order 2"); return { id: id.toString(), testOrder: true, orderLines: [] }; },
};

在控制台中,我可以查看“呼叫订单2”日志消息,没有“呼叫订单行”的日志,并且订单行数组为空。

所以分为两部分:

1)为什么在上面的示例中,它命中“ Calling order 2”而不是“ Calling order 1”?

2)为什么上述方法不适用于嵌套查询Order.OrderLines?

提前致谢!

如果使用buildSchema生成架构,则为字段提供解析器的唯一方法是通过根对象。 但这更多的是黑客-您实际上并没有覆盖字段的默认解析器,因此,您基本上只限于使用根级字段(因为您正在努力学习)。 这就是为什么只调用Query.order函数的原因-这是一个根级字段。 这里详细解释了为什么通过根(种类)传递函数。

最重要的是您不应该使用buildSchema 如果要使用SDL定义架构,请迁移到使用Apollo Server。

在查询中

type Query {
  product(id: String!): Product
  order(id: String!): Order
  users: User
}
schema {
    query: Query
}

在解析器中

const resolvers = {
  order: ({ id }) => function
  product: ({ id }) => function
}

Graphql在查询解析器概念上工作。 如果要进行任何查询(例如用户),则必须有一个解析器(即用户),该解析器返回用户类型为User的用户。 Graphql查询是交互式的并且区分大小写。下一步是为订单/产品查询实现解析器功能。 实际上,我们尚未提到的一件事是,不仅根字段而且GraphQL模式中类型上的几乎所有字段都具有解析程序功能。

1)为什么在上面的示例中,它命中“ Calling order 2”而不是“ Calling order 1”? 在此查询中

 query {
    order(id: "1") {
        id
        orderLines {
            quantity
        }
    }
 } 

然后转到订单,该订单返回具有定义类型的订单

2)为什么上述方法不适用于嵌套查询Order.OrderLines?

You can only use two query first order and second product only as per your schema

请检查doc以了解此要求的嵌套查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM