可以使用GraphQL查询中的变量来传递参数,然后在mock中使用这些变量进行处理。例如,假设我们有以下查询:
query GetProductList($category: String!, $maxPrice: Float) {
products(category: $category, maxPrice: $maxPrice) {
name
price
}
}
我们可以在mock中使用类似于以下代码的方式来处理变量:
const { MockList } = require('apollo-server');
const mocks = {
Query: () => ({
products: (root, args) => {
const { category, maxPrice } = args;
return new MockList(5, () => ({
name: 'Product name',
price: maxPrice ? Math.random() * maxPrice : Math.random() * 100,
}));
},
}),
};
在这个mock中,我们使用了args
参数获取传递的变量,然后在模拟返回的产品中根据需要使用它们。在这种情况下,我们使用了maxPrice
变量来控制返回的产品的最高价格。通过使用类似于上面的方法,我们可以预测和调整返回数据,而无需连接到实际的数据源。