Last active
December 18, 2025 13:06
-
-
Save isDipesh/1b3aa2851bb59b053a1b67f38db806e0 to your computer and use it in GitHub Desktop.
Drizzle Pagination Util
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { count } from 'drizzle-orm' | |
| const DEFAULT_PAGE_SIZE = 20 | |
| const MAX_PAGE_SIZE = 200 | |
| type PaginateableQuery<TQuery> = { | |
| limit: (limit: number | undefined) => PaginateableQuery<TQuery> | |
| offset: (offset: number | undefined) => PaginateableQuery<TQuery> | |
| orderBy: (orderBy: string) => PaginateableQuery<TQuery> | |
| } | |
| type Pagination = { | |
| page: number | |
| size: number | |
| count: number | |
| pages: number | |
| } | |
| export async function paginateResults<TQuery>( | |
| query: TQuery, | |
| page = 1, | |
| size = DEFAULT_PAGE_SIZE, | |
| ) { | |
| if (size > MAX_PAGE_SIZE) { | |
| size = MAX_PAGE_SIZE | |
| } | |
| const offset = (page - 1) * size | |
| const results = await (query as PaginateableQuery<TQuery>) | |
| .limit(size) | |
| .offset(offset) | |
| // @ts-expect-error - config is available in runtime but not in type | |
| query.config.fields = { resultCount: count() } | |
| const [{ resultCount }] = await ( | |
| query as PaginateableQuery<TQuery> | |
| ) | |
| .limit(undefined) | |
| .offset(undefined) | |
| .orderBy('1') as unknown as { resultCount: number }[] | |
| const pages = Math.ceil(resultCount / size) | |
| if (page > pages) { | |
| throw new Error('Page not found') | |
| } | |
| return { | |
| results: results as unknown as Awaited<Promise<TQuery>>, | |
| pagination: { | |
| page, | |
| size, | |
| count: resultCount, | |
| pages, | |
| } as Pagination, | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage:
Example Response:
{ "results": [ { "id": 6, "title": "Article 6", "publishedAt": 1699992000000 }, { "id": 7, "title": "Article 7", "publishedAt": 1699995600000 }, { "id": 8, "title": "Article 8", "publishedAt": 1699999200000 }, { "id": 9, "title": "Article 9", "publishedAt": 1700002800000 }, { "id": 10, "title": "Article 10", "publishedAt": 1700006400000 } ], "pagination": { "page": 2, "size": 5, "count": 12, "pages": 3 } }Drizzle Pagination Util for Nuxt/Nitro - https://gist.github.com/isDipesh/fdfd5197e89447a9ed6ee48338fe3f5f