name: api-filtering-sorting description: 构建灵活的API过滤和排序系统,包括查询参数解析、验证和安全。用于实现搜索端点、构建数据网格或创建动态查询API。
API过滤与排序
构建灵活的过滤和排序系统,高效处理复杂查询。
查询参数语法
GET /products?category=electronics&price[gte]=100&price[lte]=500&sort=-price,name
实现 (Node.js)
const allowedFilters = ['category', 'status', 'price', 'createdAt'];
const allowedSorts = ['name', 'price', 'createdAt'];
app.get('/products', async (req, res) => {
const filter = {};
const sort = {};
// 解析过滤器
for (const [key, value] of Object.entries(req.query)) {
if (key === 'sort') continue;
const match = key.match(/^(\w+)\[(\w+)\]$/);
if (match) {
const [, field, operator] = match;
if (!allowedFilters.includes(field)) continue;
filter[field] = { [`$${operator}`]: parseValue(value) };
} else if (allowedFilters.includes(key)) {
filter[key] = value;
}
}
// 解析排序
if (req.query.sort) {
for (const field of req.query.sort.split(',')) {
const direction = field.startsWith('-') ? -1 : 1;
const name = field.replace(/^-/, '');
if (allowedSorts.includes(name)) sort[name] = direction;
}
}
const products = await Product.find(filter).sort(sort);
res.json({ data: products });
});
function parseValue(value) {
if (value === 'true') return true;
if (value === 'false') return false;
if (!isNaN(value)) return Number(value);
return value;
}
过滤器运算符
| 运算符 | 含义 | 示例 |
|---|---|---|
| eq | 等于 | ?status=active |
| ne | 不等于 | ?status[ne]=deleted |
| gt/gte | 大于/大于等于 | ?price[gte]=100 |
| lt/lte | 小于/小于等于 | ?price[lte]=500 |
| in | 在数组中 | ?status[in]=active,pending |
| like | 包含 | ?name[like]=phone |
安全
- 白名单允许的过滤器字段
- 验证每个字段的输入类型
- 索引频繁过滤的列
- 限制查询复杂度
- 防止SQL/NoSQL注入
最佳实践
- 支持常用运算符
- 缓存过滤器选项列表
- 监控查询性能
- 提供合理的默认值