gpt4 book ai didi

graphql - Apollo GraphQL 中带有变量的嵌套查询

转载 作者:行者123 更新时间:2023-12-04 15:29:47 25 4
gpt4 key购买 nike

我正在使用 Apollo 服务器,尝试为电子商务应用程序构建嵌套查询。我正在查询 rest 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!\".", .

任何帮助表示赞赏!

最佳答案

使用父参数解决了这个问题,而不是将任何变量传递给子查询。

//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
}
}
}

关于graphql - Apollo GraphQL 中带有变量的嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51958018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com