Skip to content

Instantly share code, notes, and snippets.

@waptik
Last active March 27, 2021 07:47
Show Gist options
  • Save waptik/880ea39fe49624747b8658a89ea3bce0 to your computer and use it in GitHub Desktop.
Save waptik/880ea39fe49624747b8658a89ea3bce0 to your computer and use it in GitHub Desktop.
A simple pagination helper function for prisma 2
/**
* 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
@waptik
Copy link
Author

waptik commented Mar 27, 2021

Usage:

import {paginate} from "utils" // import the function from where it's saved

  const page = parseInt(req.query.page as string, 10) || 1
  const take = 2
  const skip = take * Number(page)

  const data = await paginate({
    name: "user", // model name
    where: { isActive: true },
    take,
    page,
    orderBy: {createdAt: "desc"},
  })

console.log({data})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment