【问题标题】:Nested query with variable in Apollo GraphQLApollo GraphQL 中带有变量的嵌套查询
【发布时间】:2019-01-28 04:38:20
【问题描述】:

我正在使用 Apollo 服务器,尝试为电子商务应用程序构建嵌套查询。我正在查询一个休息 api 来检索购物篮中的物品。

但是,此请求的响应并未包含我们需要的所有产品信息。所以我试图嵌套一个额外的查询,使用返回的参数之一作为变量来获取所需的额外产品信息。

我看过嵌套查询示例,据我所知(我对 GraphQL 和 Apollo 很陌生),这是 GraphQL 的一大优点。但我还没有看到任何嵌套查询依赖于父查询返回值的示例。

//typeDefs
const typeDefs = gql`
    type Product {
        id: ID
        name: String
        sku: String
        length: Float
    }
    type CartItem {
        id: ID
        product_id: ID
        quantity: Int
        product(product_id: ID!): Product
    }
    type Query {
        getProduct(id: ID!): Product
        getCartItems(id: ID!): [CartItem]
    }
`;
// resolvers
const processResponse = (resolved) => {
    try {
        const { data } = resolved;
        return data;
    } catch (error) {
        return error;
    }
};
const resolvers = {
    Query: {
        getProduct: async (parent, { id }, { ctx }) => {
            return processResponse(await ctx.get(`products/${id}`));
        },
        getCartItems: async (parent, { id }, { ctx }) => {
            return processResponse(await ctx.get(`carts/${id}/items`))
        }
    },
    CartItem: {
        product: async (parent, { product_id }, { ctx }) => {
            return processRequest(await ctx.get(`products/${product_id}`));
        }
    }
};

// and query in the playground
query {
  getCartItems(id:"1234b11") {
    id
    product_id
    quantity
    product(product_id: $product_id) {
      id
      name
      description
    }
  } 
}

我得到的错误是 Variable \"$product_id\" is not defined." 当我用实际的 product_id 对 product_id 进行硬编码时,我得到了我想要的那种响应,但这当然不是动态的。我尝试将变量传递给查询,例如query ($product_id: ID),但我收到错误"Variable \"$product_id\" of type \"ID\" used in position expecting type \"String!\".",

任何帮助表示赞赏!

【问题讨论】:

    标签: graphql apollo-server


    【解决方案1】:

    使用父参数解决了这个问题,并且没有将任何变量传递给子查询。

    //typeDefs
    type CartItem {
        id: ID
        product_id: ID
        quantity: Int
        product: Product
    }
    //resolver
    getCartItems: async (parent, { id }, { ctx }) => {
        return processResponse(await ctx.get(`carts/${id}/items`))
            },
    CartItem: {
        product: async (parent, args, { ctx }) => {
        const productId = parent.product_id;
        if (productId) {
          const { data } = processResponse(await ctx.get(`products/${productId}`));
          return data
        }
    }
    //query
    query {
      getCartItems(id:"1234b11") {
        id
        product_id
        quantity
        product {
          id
          name
          description
        }
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2018-03-02
      • 2020-04-24
      • 1970-01-01
      • 2017-02-21
      • 2019-01-02
      • 2019-01-17
      • 2020-08-01
      • 1970-01-01
      相关资源
      最近更新 更多