如何在GraphQL中通过ID数组过滤并获取指定商品列表?
按ID数组过滤商品的GraphQL Schema实现方案
要实现传入ID数组过滤商品的需求,你需要在GraphQL Schema中定义带参数的查询字段,并编写对应的解析函数处理过滤逻辑,具体步骤如下:
1. 定义Schema类型结构
首先明确Product类型和支持ID数组参数的查询字段,用[ID!]!声明参数类型(表示这是非空的必填ID数组):
# 定义商品类型 type Product { id: ID! title: String! description: String! price: Float! } # 定义查询类型,添加接收ID数组的查询字段 type Query { productsByIds(ids: [ID!]!): [Product!]! }
2. 编写解析函数
在解析器中,针对productsByIds字段实现过滤逻辑,从数据源中筛选出ID在传入数组中的商品:
// 假设商品数据源是题目给出的products数组 const products = [ { id: '001', title: 'Product 01', description: 'Some cool product', price: 50.00 }, { id: '002', title: 'Product 02', description: 'Some cool product', price: 50.00 }, { id: '003', title: 'Product 03', description: 'Some cool product', price: 50.00 }, { id: '004', title: 'Product 04', description: 'Some cool product', price: 50.00 }, { id: '005', title: 'Product 05', description: 'Some cool product', price: 50.00 } ]; const resolvers = { Query: { productsByIds: (_, { ids }) => { // 用filter方法筛选出id存在于传入数组中的商品 return products.filter(product => ids.includes(product.id)); } } };
3. 查询调用示例
编写GraphQL查询时,传入目标ID数组即可获取过滤后的商品:
query GetTargetProducts { productsByIds(ids: ["001", "003", "004"]) { id title price } }
执行该查询后,会仅返回ID为001、003、004的三个商品数据。
内容的提问来源于stack exchange,提问作者Optiq
相关产品推荐
相关产品推荐

