import { map } from 'lodash' export type List = { items: T[] page: number next: number limit: number total: number } export type ListConfig = { limit?: number sort?: string // field key direction?: 'asc' | 'desc' page?: number // starts from 1 search?: { keywords: string fields: string[] } } export const paginate = (items: T[], config: ListConfig, total: number): List => { const { limit, page } = config const skip = limit * (page - 1) const finalItems = items.slice(skip, skip + limit) const hasNext = page * limit < total const next = hasNext ? page + 1 : null return { items: finalItems, page, next, limit, total, } } const defaultListConfig: ListConfig = { limit: 10, sort: 'id', direction: 'desc', page: 1, } export const queryItems = < T extends { id?: string createdAt?: string } >( itemsDict: { [id: string]: T }, listConfig: ListConfig, total: number, ) => { const config = { ...defaultListConfig, ...listConfig, } return paginate( map(itemsDict).sort( (a, b) => new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf(), ), config, total, ) }