Implement filtering and sorting from query parameters
Implement filtering and sorting from query parameters with an allowlist of fields, so a client cannot sort or filter on columns you did not expose.
List endpoints usually accept status=open for filtering and sort=-priority for ordering. The server should accept only fields it has chosen to expose.
const items = [
{ title: 'A', status: 'open', priority: 1 },
{ title: 'B', status: 'closed', priority: 3 },
{ title: 'C', status: 'open', priority: 2 },
];
const FILTERABLE = ['status'];
const SORTABLE = ['priority', 'title'];
function query(rows, params) {
let result = rows;
for (const field of FILTERABLE) {
if (params.has(field)) result = result.filter((r) => r[field] === params.get(field));
}
const sort = params.get('sort');
if (sort) {
const desc = sort.startsWith('-');
const field = desc ? sort.slice(1) : sort;
if (!SORTABLE.includes(field)) throw new Error(`Cannot sort by ${field}`);
result = [...result].sort((a, b) => (a[field] > b[field] ? 1 : -1) * (desc ? -1 : 1));
}
return result;
}
console.log(query(items, new URLSearchParams('status=open&sort=-priority')).map((r) => r.title));[ 'C', 'A' ]The leading minus for descending order is a common convention, borrowed from JSON:API. Only the open items remain, and they are ordered by priority from high to low.
The allowlists are the security feature. If the field name from the request went straight into an SQL ORDER BY, a client could sort on a private column or inject SQL; with an allowlist, anything else is an error you can turn into a 400. For a database, map each allowed name to a column and use parameters for values.