Last active
March 27, 2021 07:47
-
-
Save waptik/880ea39fe49624747b8658a89ea3bce0 to your computer and use it in GitHub Desktop.
A simple pagination helper function for prisma 2
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
/** | |
* This is custom pagination helper that | |
* works with prisma 2 | |
* @author @_waptik | |
*/ | |
import db from "db" // xutom prisma wrapper by blitz-js | |
interface Paginate { | |
name: string | |
by?: string | |
where?: Record<string, any> | |
take?: number | |
cursor?: string | |
direction?: "asc" | "desc" | |
page?: number | |
orderBy?: Record<string, any> | |
} | |
async function paginate({ name, where = {}, take = 2, cursor, page = 1, orderBy }: Paginate) { | |
if (!orderBy) { | |
orderBy = { | |
createdAt: "asc", | |
} | |
} | |
const skip = cursor ? 1 : (page - 1) * take | |
const conditions = { | |
where, | |
take, | |
skip, | |
orderBy, | |
cursor: cursor ? { id: cursor } : undefined, | |
} | |
const model = db[name.toLowerCase()] | |
const total = await model.count() | |
const nodes = await model.findMany(conditions) | |
const pages = take > 0 ? Math.ceil(total / take) || 1 : null | |
const next = page < pages! ? page + 1 : null | |
const prev = page > 1 ? page - 1 : null | |
return { | |
nodes, | |
pagination: { | |
total, | |
current: page, | |
next, | |
prev, | |
pages, | |
}, | |
} | |
} | |
export default paginate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: