Skip to content

Commit 2d31566

Browse files
committed
refactor(pagination): extract pagination in dedicated handler
1 parent 49574cf commit 2d31566

1 file changed

Lines changed: 23 additions & 19 deletions

File tree

src/query.ts

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,25 +10,7 @@ export function query<T extends GenericObject, P extends QueryParams<T>>(
1010
if (params.sort)
1111
result = sortedQuery(result, params.sort)
1212

13-
if (typeof params.limit === 'undefined') {
14-
return { rows: result } as QueryResult<T, P>
15-
}
16-
17-
else {
18-
const unpaginatedRows = [...result]
19-
const totalRows = result.length
20-
const totalPages = Math.ceil(totalRows / params.limit)
21-
const start = ((params?.page ?? 1) - 1) * params.limit
22-
const end = start + params.limit
23-
result = result.slice(start, end)
24-
25-
return {
26-
totalRows,
27-
totalPages,
28-
rows: result,
29-
unpaginatedRows,
30-
} as QueryResult<T, P>
31-
}
13+
return paginateQuery(result, params)
3214
}
3315

3416
function* lazyQuery<T extends GenericObject>(data: T[], params: QueryParams<T>): Generator<T> {
@@ -96,3 +78,25 @@ function sortedQuery<T extends GenericObject>(data: T[], sortOptions?: QueryPara
9678
return 0
9779
})
9880
}
81+
82+
function paginateQuery<T extends GenericObject, P extends QueryParams<T>>(data: T[], params: P): QueryResult<T, P> {
83+
if (typeof params.limit === 'undefined') {
84+
return { rows: data } as QueryResult<T, P>
85+
}
86+
87+
else {
88+
const unpaginatedRows = [...data]
89+
const totalRows = data.length
90+
const totalPages = Math.ceil(totalRows / params.limit)
91+
const start = ((params?.page ?? 1) - 1) * params.limit
92+
const end = start + params.limit
93+
data = data.slice(start, end)
94+
95+
return {
96+
totalRows,
97+
totalPages,
98+
rows: data,
99+
unpaginatedRows,
100+
} as QueryResult<T, P>
101+
}
102+
}

0 commit comments

Comments
 (0)