sorting-query
Version:
An utility to parse and define types of sorting queries
33 lines (29 loc) • 1.95 kB
text/typescript
declare const SORT_PREFIX: "orderBy.";
type TKey = string | number | symbol;
type Values<T> = T[keyof T];
type SortedColumn<T> = {
key: T;
order: "asc" | "desc";
};
type Comparator<T> = (a: T, b: T) => number;
type AscendingComparatorsDict<V extends object, K extends keyof V> = {
[key in K]: Comparator<V[key]>;
};
type SortedPropertiesFromParams<Obj> = Values<{
[key in keyof Obj]-?: key extends `${typeof SORT_PREFIX}${infer K}` ? K : never;
}>;
type OrderByParams<T extends string> = {
[key in `${typeof SORT_PREFIX}${T}`]: "asc" | "desc";
};
declare function indifferentComparator<T>(a: T, b: T): number;
declare function getSorted<V extends object, K extends keyof V>(ascendingComparators: AscendingComparatorsDict<V, K>, orderBy: SortedColumn<K>[], items: V[]): V[];
declare function numberAscending(a: number, b: number): number;
declare function stringAscending<T extends string | undefined>(a: T, b: T): number;
declare function timestampNewerFirst(a: number, b: number): number;
declare function isValidOrder(value: unknown): value is "asc" | "desc";
declare function isSortQueryParam(value: unknown): value is `${typeof SORT_PREFIX}${string}`;
declare function getSortedProperty<P extends string>(value: `${typeof SORT_PREFIX}${P}`): P;
declare function parseSortingParams<Obj extends object>(params: Obj): SortedColumn<SortedPropertiesFromParams<Obj>>[];
declare function isValidSortedColumns<T extends TKey>(sortableKeys: readonly T[], value: any): value is SortedColumn<T>[];
declare function toQueryParams<T extends TKey>(sortedColumns: SortedColumn<T>[]): Record<string, string>;
export { AscendingComparatorsDict, Comparator, OrderByParams, SORT_PREFIX, SortedColumn, SortedPropertiesFromParams, TKey, Values, getSorted, getSortedProperty, indifferentComparator, isSortQueryParam, isValidOrder, isValidSortedColumns, numberAscending, parseSortingParams, stringAscending, timestampNewerFirst, toQueryParams };