2020-06-26 21:25:03 +00:00
|
|
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
|
|
|
|
import { Request } from 'express'
|
|
|
|
|
|
|
|
export interface PaginateQuery {
|
|
|
|
page?: number
|
|
|
|
limit?: number
|
|
|
|
sortBy?: [string, string][]
|
2020-06-28 17:34:00 +00:00
|
|
|
search?: 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-28 17:34:00 +00:00
|
|
|
const sortBy: [string, string][] = []
|
2020-06-26 21:25:03 +00:00
|
|
|
if (query.sortBy) {
|
2020-06-26 22:14:35 +00:00
|
|
|
const params = !Array.isArray(query.sortBy) ? [query.sortBy] : query.sortBy
|
2020-06-28 17:34:00 +00:00
|
|
|
for (const param of params as string[]) {
|
|
|
|
if (typeof param === 'string') {
|
2020-06-26 22:14:35 +00:00
|
|
|
const items = param.split(':')
|
|
|
|
if (items.length === 2) {
|
2020-06-28 17:34:00 +00:00
|
|
|
sortBy.push(items as [string, string])
|
2020-06-26 22:14:35 +00:00
|
|
|
}
|
2020-06-26 21:25:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
page: query.page ? parseInt(query.page.toString(), 10) : undefined,
|
|
|
|
limit: query.limit ? parseInt(query.limit.toString(), 10) : undefined,
|
2020-06-28 17:34:00 +00:00
|
|
|
sortBy: sortBy.length ? sortBy : undefined,
|
2020-06-28 17:50:08 +00:00
|
|
|
search: query.search ? query.search.toString() : undefined,
|
2020-06-26 21:25:03 +00:00
|
|
|
path,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|