nestjs-paginate/src/decorator.ts

51 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-06-26 21:25:03 +00:00
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { Request } from 'express'
2021-08-19 14:42:18 +00:00
import { pickBy, Dictionary, isString, mapKeys } from 'lodash'
2020-06-26 21:25:03 +00:00
export interface PaginateQuery {
page?: number
limit?: number
sortBy?: [string, string][]
2020-06-28 17:34:00 +00:00
search?: string
2021-08-19 14:42:18 +00:00
filter?: { [column: string]: string | string[] }
2020-06-26 21:25:03 +00:00
path: string
}
export const Paginate = createParamDecorator((_data: unknown, ctx: ExecutionContext): PaginateQuery => {
const request: Request = ctx.switchToHttp().getRequest()
const { query } = request
const path = request.protocol + '://' + request.get('host') + request.baseUrl + request.path
2020-06-26 21:25:03 +00:00
const sortBy: [string, string][] = []
if (query.sortBy) {
const params = !Array.isArray(query.sortBy) ? [query.sortBy] : query.sortBy
2021-08-19 14:42:18 +00:00
for (const param of params) {
if (isString(param)) {
const items = param.split(':')
if (items.length === 2) {
sortBy.push(items as [string, string])
2020-06-26 21:25:03 +00:00
}
}
}
}
2020-06-26 21:25:03 +00:00
2021-08-19 14:42:18 +00:00
const filter = mapKeys(
pickBy(
query,
(param, name) =>
name.includes('filter.') &&
(isString(param) || (Array.isArray(param) && (param as any[]).every((p) => isString(p))))
) as Dictionary<string | string[]>,
(_param, name) => name.replace('filter.', '')
)
return {
page: query.page ? parseInt(query.page.toString(), 10) : undefined,
limit: query.limit ? parseInt(query.limit.toString(), 10) : undefined,
sortBy: sortBy.length ? sortBy : undefined,
search: query.search ? query.search.toString() : undefined,
2021-08-19 14:42:18 +00:00
filter: Object.keys(filter).length ? filter : undefined,
path,
2020-06-26 21:25:03 +00:00
}
})