mirror of
https://github.com/ershisan99/flashcards-api.git
synced 2025-12-17 12:33:22 +00:00
fix pagination and create pagination service
This commit is contained in:
8
src/infrastructure/common/helpers/set-count-key.ts
Normal file
8
src/infrastructure/common/helpers/set-count-key.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { omit } from 'remeda'
|
||||
|
||||
export const setCountKey = <K extends string, L extends string>(key: K, newKey: L) => {
|
||||
return <T extends Record<string, any>>(obj: T) => {
|
||||
obj[newKey] = obj['_count'][key]
|
||||
return omit(obj, ['_count']) as Omit<T, '_count'> & { [P in L]: number }
|
||||
}
|
||||
}
|
||||
@@ -10,5 +10,5 @@ export class PaginationDto {
|
||||
@Type(() => Number)
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
pageSize?: number
|
||||
itemsPerPage?: number
|
||||
}
|
||||
|
||||
@@ -1,9 +1,43 @@
|
||||
import { isObject } from 'remeda'
|
||||
|
||||
export class Pagination {
|
||||
static getPaginationData(query) {
|
||||
const page = typeof query.PageNumber === 'string' ? +query.PageNumber : 1
|
||||
const pageSize = typeof query.PageSize === 'string' ? +query.PageSize : 10
|
||||
const searchNameTerm = typeof query.SearchNameTerm === 'string' ? query.SearchNameTerm : ''
|
||||
const searchEmailTerm = typeof query.SearchEmailTerm === 'string' ? query.SearchEmailTerm : ''
|
||||
return { page, pageSize, searchNameTerm, searchEmailTerm }
|
||||
static getPaginationData<T>(query: T) {
|
||||
if (!isObject(query)) throw new Error('Pagination.getPaginationData: query is not an object')
|
||||
|
||||
const currentPage =
|
||||
'currentPage' in query &&
|
||||
typeof query.currentPage === 'string' &&
|
||||
!isNaN(Number(query.currentPage))
|
||||
? +query.currentPage
|
||||
: 1
|
||||
const itemsPerPage =
|
||||
'itemsPerPage' in query &&
|
||||
typeof query.itemsPerPage === 'string' &&
|
||||
!isNaN(Number(query.itemsPerPage))
|
||||
? +query.itemsPerPage
|
||||
: 10
|
||||
return { currentPage, itemsPerPage, ...query }
|
||||
}
|
||||
|
||||
static transformPaginationData<T>(
|
||||
[count, items]: [number, T],
|
||||
{
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
}: {
|
||||
currentPage: number
|
||||
itemsPerPage: number
|
||||
}
|
||||
) {
|
||||
const totalPages = Math.ceil(count / itemsPerPage)
|
||||
return {
|
||||
pagination: {
|
||||
totalPages,
|
||||
currentPage,
|
||||
itemsPerPage,
|
||||
totalItems: count,
|
||||
},
|
||||
items,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user