type QueryFilterPrimitive = string | number | boolean | null; export type QueryFilterValue = QueryFilterPrimitive | undefined | readonly QueryFilterPrimitive[]; export type QuerySortValue = -1 | 0 | 1 | 'asc' | 'desc' | null | undefined; export interface QueryBuilderParams { page?: number; filters?: { [K in FilterKeys]?: QueryFilterPrimitive | Readonly; }; sorts?: { [K in SortKeys]?: Exclude; }; } export const queryFilterValue = (value: QueryFilterValue) => { if (value === undefined || value === null || value === '') { return; } const normalized = Array.isArray(value) ? value.join(',') : String(value); return normalized.length > 0 ? normalized : undefined; }; export const querySortValue = (field: string, value: QuerySortValue) => { if (!value || !['asc', 'desc', 1, -1].includes(value)) { return; } return value === -1 || value === 'desc' ? `-${field}` : field; }; export const querySortList = (sorts: Partial> | undefined) => { if (!sorts) { return []; } return (Object.entries(sorts) as [TSort, QuerySortValue][]).flatMap(([field, value]) => { const sort = querySortValue(field, value); return sort ? [sort] : []; }); }; export type ListSort = TField | `-${TField}`; export const listSorts = ( fields: readonly TField[], sort: ListSort | undefined ): Partial> | undefined => { const descending = sort?.startsWith('-') === true; const field = fields.find((candidate) => candidate === (descending ? sort?.slice(1) : sort)); if (field === undefined) { return undefined; } const sorts: Partial> = {}; sorts[field] = descending ? 'desc' : 'asc'; return sorts; }; export type ListQuery = Partial> & { page?: number; per_page?: number; sort?: string; }; export const listQuery = ( params: QueryBuilderParams = {}, perPage?: number ): ListQuery => { const filters: Partial> = {}; for (const [field, value] of Object.entries(params.filters ?? {}) as [TFilter, QueryFilterValue][]) { const normalized = queryFilterValue(value); if (normalized !== undefined) { filters[`filter[${field}]` as const] = normalized; } } const query: ListQuery = { ...filters }; const sorts = querySortList(params.sorts); if (sorts.length > 0) { query.sort = sorts.join(','); } if (params.page !== undefined) { query.page = params.page; } if (perPage !== undefined) { query.per_page = perPage; } return query; };