DEV Community

Cover image for Express js pagination dengan prisma
Andi Ismail
Andi Ismail

Posted on

Express js pagination dengan prisma

Express pagination lanjutan penabahasan sebelumnya,

github repo sebelumnya disini

node module dan database tidak disertakan di github, jadi setelah

git clone

npm install
npx prisma db push
Enter fullscreen mode Exit fullscreen mode

Image error env

error environment tidak ditemukan, kita harus buat dulu envnya.

//.env

DATABASE_URL = "file:./db.sqlite"
PORT= 9000

Enter fullscreen mode Exit fullscreen mode

coba kita jalankan kembali

npx prisma db push

Image berhasil clone

sekarang kita jalankan server

npm run dev

Image run dev

server sudah berhasil berjalan...

Image ganti

kalau kita hit kembali dengan data yang sama maka akan error karena username dan email uniq.

Image error unique

//package.json

{
  "name": "express_faker",
  "version": "1.0.0",
  "description": "",
  "main": "/src/index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./src/index.js",
    "users_seed" : "babel-node ./src/seeds/users_seed.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@prisma/client": "^4.7.1",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "prisma": "^4.7.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/node": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "@faker-js/faker": "^7.6.0"
  }
}

Enter fullscreen mode Exit fullscreen mode

dipackage json kita sudah tambahkan user_seed untuk menambahkan 100 data faker.
matikan servernya dan ketikkan

npm run users_seed

Image 100data

sekarang dua server yang berjalan.

npm run users_seed
npm run dev
Enter fullscreen mode Exit fullscreen mode

kalau kita hit di tester.rest maka akan produksi 100 data plus data input yang kita lakukan sebelumnya, oleh karenaya kita akan membuat pagination untuk memudah kinerja load data. kita akan ke controller user fokus pada user read

Image send request

di findmany kasih objek take=10

//user_controller.js

import db from "../../prisma/connection"
import { request, response } from "express"

// create user
export const user_create = async (req = request, res = response) => {
    try {
        const data = await req.body
        const createUser = await db.users.create({
            data: data
        })
        return res.status(201).json({
            success: true,
            message: "User berhasil di buat"
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}

// user read
export const user_read = async (req = request, res = response) => {
    try {
        const result = await db.users.findMany({
            take : 10 //tambahkan ini
        })
        return res.status(200).json({
            success: true,
            data: result
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

sekarang ke tester.rest kalau kita send request untuk read data, hasilya kita hanya akan melihat 10 data saja

Image 10 data

kalau kita kasih take 10 dan skip 10 maka akan menampilkan 10 data di setiap halaman nnya.

//user_controller.js

import db from "../../prisma/connection"
import { request, response } from "express"

// create user
export const user_create = async (req = request, res = response) => {
    try {
        const data = await req.body
        const createUser = await db.users.create({
            data: data
        })
        return res.status(201).json({
            success: true,
            message: "User berhasil di buat"
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}

// user read
export const user_read = async (req = request, res = response) => {
    try {
        const result = await db.users.findMany({
            take : 10,
            skip:10

        })
        return res.status(200).json({
            success: true,
            data: result
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

Image mulai dari 11

selanjutnya kita akan buat variable untuk page

//user_controller.js

import db from "../../prisma/connection"
import { request, response } from "express"

// create user
export const user_create = async (req = request, res = response) => {
    try {
        const data = await req.body
        const createUser = await db.users.create({
            data: data
        })
        return res.status(201).json({
            success: true,
            message: "User berhasil di buat"
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}

// user read
export const user_read = async (req = request, res = response) => {
    try {

        // let page =1
        // let limit = 10
        let {page=1, limit=10}= req.query //menghasilkan string
        let skip = (page-1) * limit
        const result = await db.users.findMany({
            //take : 10,
            take : parseInt(limit),
            //skip:10
            skip:skip

        })
        return res.status(200).json({
            success: true,
            data: result
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

sekarang coba kita hit, tanpa query kita sebelumnya sudah memberikan nilai default 1-10.

Image 1-10

Image 2-5

berhasil

//user_controller.js

import db from "../../prisma/connection"
import { request, response } from "express"

// create user
export const user_create = async (req = request, res = response) => {
    try {
        const data = await req.body
        const createUser = await db.users.create({
            data: data
        })
        return res.status(201).json({
            success: true,
            message: "User berhasil di buat"
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}

// user read
export const user_read = async (req = request, res = response) => {
    try {

        // let page =1
        // let limit = 10
        let {page=1, limit=10}= req.query //menghasilkan string
        let skip = (page-1) * limit
        const result = await db.users.findMany({
            //take : 10,
            take : parseInt(limit),
            //skip:10
            skip:skip
        })

        //informasi total data keseluruhan 
        const resultCount = await db.users.count()//integer jumlah total data user

        //generated total page
        const totalPage= Math.ceil(resultCount/limit)

        return res.status(200).json({
            success: true,
            current_page: page - 0, //ini -0 merubah menjadi integer
            total_page : totalPage,
            total_data : resultCount,
            data: result
        })
    } catch (error) {
        return res.status(500).json({
            success: false,
            error: error.message
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

code di atas akan menmpikan jumlah page, current page, total data dan total page.

Image page3

berhasil.

github repo

Top comments (0)