api-filtering-sorting

v2026.09.24

Builds flexible API filtering and sorting systems with query parameter parsing, validation, and security. Use when implementing search endpoints, building data grids, or creating dynamic query APIs.

GitHub
安装命令
npx skhub add secondsky/api-filtering-sorting
Markdown
SKILL.md

API Filtering & Sorting

Build flexible filtering and sorting systems that handle complex queries efficiently.

Query Parameter Syntax

GET /products?category=electronics&price[gte]=100&price[lte]=500&sort=-price,name

Implementation (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;
}

Filter Operators

OperatorMeaningExample
eqEquals?status=active
neNot equals?status[ne]=deleted
gt/gteGreater than?price[gte]=100
lt/lteLess than?price[lte]=500
inIn array?status[in]=active,pending
likeContains?name[like]=phone

Security

  • Whitelist allowed filter fields
  • Validate input types per field
  • Index frequently-filtered columns
  • Limit query complexity
  • Prevent SQL/NoSQL injection

Best Practices

  • Support common operators
  • Cache filter option lists
  • Monitor query performance
  • Provide sensible defaults
发现
标签

此技能尚未发布标签。

版本
最新版本元数据

版本

v2026.09.24

发布时间

Sep 24, 2026

分类

未分类

许可证

MIT

源路径

plugins/api-filtering-sorting/skills/api-filtering-sorting

默认分支

main

最新提交

a0994f7

Tree SHA

6c0d7e0