关于 api-filtering-sorting
面向 API 开发者的过滤与排序实践指南,涵盖查询运算符、字段白名单、输入验证和查询安全。
主要功能
- 01相等与范围过滤运算符
- 02多字段排序语法
- 03字段白名单与输入验证
- 04查询复杂度与注入防护
适用场景
- 01为商品 API 添加过滤
- 02按多个字段排序结果
- 03限制用户可提交的查询字段
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill api-filtering-sorting安装后在 Claude Code 中输入/api-filtering-sorting确认已加载。
详细介绍
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 = {};
// Parse filters
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;
}
}
// Parse sort
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 注入
最佳实践
- 支持常用运算符
- 缓存筛选选项列表
- 监控查询性能
- 提供合理的默认值
评论
支持 Markdown