Nauxscript
Nauxscript
DTDrizzle Team
Created by Nauxscript on 11/28/2023 in #help
how to encapsulate a general pagination function
I am looking to create a generalized pagination function to simplify the implementation of APIs with pagination capabilities. Here's the code I'm currently using:
// api route
const routes = {
list: async (page: number, size: number) => {
// ...
const query = db.select()
.from(billings)
.orderBy(desc(billings.transactionAt))
const dynamicQuery = query.$dynamic()
const res = await withPagination(dynamicQuery, page, size)
return res
}
}

const withPagination = (
query: PgSelect,
page: number,
size: number
) => {
const all = await query
const count = all.length
const currentTailIndex = page * size
const currentHeadIndex = currentTailIndex - size
const meta: PageMeta = {
currentPage: page,
isFirstPage: page === 1,
isLastPage: currentTailIndex >= count,
previousPage: page - 1 === 0 ? null : page - 1,
nextPage: currentTailIndex >= count ? null : page + 1,
pageCount: Math.ceil(count / size),
}

const res = all.slice(currentHeadIndex, size)
return {
...meta,
data: res,
}
}
// api route
const routes = {
list: async (page: number, size: number) => {
// ...
const query = db.select()
.from(billings)
.orderBy(desc(billings.transactionAt))
const dynamicQuery = query.$dynamic()
const res = await withPagination(dynamicQuery, page, size)
return res
}
}

const withPagination = (
query: PgSelect,
page: number,
size: number
) => {
const all = await query
const count = all.length
const currentTailIndex = page * size
const currentHeadIndex = currentTailIndex - size
const meta: PageMeta = {
currentPage: page,
isFirstPage: page === 1,
isLastPage: currentTailIndex >= count,
previousPage: page - 1 === 0 ? null : page - 1,
nextPage: currentTailIndex >= count ? null : page + 1,
pageCount: Math.ceil(count / size),
}

const res = all.slice(currentHeadIndex, size)
return {
...meta,
data: res,
}
}
However, I'm encountering an issue where the type of res is lost. Is there a way to ensure that the result maintains the original table column types?
2 replies