API过滤与排序 api-filtering-sorting

API过滤与排序技能用于后端开发中构建灵活的API查询系统,通过查询参数解析和验证,实现安全高效的过滤和排序功能,常用于搜索端点、数据网格和动态API开发。关键词:API过滤,排序,查询参数,后端开发,数据安全,性能优化。

后端开发 0 次安装 0 次浏览 更新于 3/8/2026

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注入

最佳实践

  • 支持常用运算符
  • 缓存过滤器选项列表
  • 监控查询性能
  • 提供合理的默认值