Express js pagination dengan prisma
Published: 2022-12-11 14:11:04

Express pagination lanjutan penabahasan sebelumnya, 

[github repo sebelumnya disini](https://github.com/andiks2018/JvalleyExpress-SeddFakerJs.git)

node module dan database tidak disertakan di github, jadi setelah

`git clone` 

```
npm install
npx prisma db push
```

![Image error env](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tbva9hbkqkgmbpplrqq0.png)

error environment tidak ditemukan, kita harus buat dulu envnya.

```
//.env

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

```
coba kita jalankan kembali 

`npx prisma db push`

![Image berhasil clone](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0f5rr89k4p3gpqcyy8sh.png)

sekarang kita jalankan server 

`npm run dev`

![Image run dev](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1u2o92wtmhjm6p99wh1.png)

server sudah berhasil berjalan...

![Image ganti](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vhci63j6ohaa2joiow6u.gif)

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

![Image error unique](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/164blyqtm88k8pc4sca6.png)

```
//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"
  }
}

```

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

`npm run users_seed`

![Image 100data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d2rlhn1yd4yzs4tfdeqt.png)

sekarang dua server yang berjalan.

```
npm run users_seed
npm run dev
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5v4lrvg7n7bzcls8uz4e.png)

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
        })
    }
}
```
sekarang ke tester.rest kalau kita send request untuk read data, hasilya kita hanya akan melihat 10 data saja

![Image 10 data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ty92tr4wfkdtc51d896.png)

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
        })
    }
}
```

![Image mulai dari 11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utl94q7v1mxdozk0gux3.png)

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
        })
    }
}
```
sekarang coba kita hit, tanpa query kita sebelumnya sudah memberikan nilai default 1-10.

![Image 1-10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrsjqkfwb1j6gy7ebr7u.gif)

![Image 2-5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p02qtoq37d4jtt42tdl3.gif)

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
        })
    }
}
```
code di atas akan menmpikan jumlah page, current page, total data dan total page.

![Image page3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5t2tc04xyrij7pwtnh1.gif)

berhasil.

[github repo](https://github.com/andiks2018/JvalleyExpress-pagination.git)