Express postman
Published: 2022-12-12 16:49:20


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

```
mkdir express_sample_api
npm init -y
npm install express dotenv prisma
npm install -D @babel/core @babel/node @babel/preset-env @faker-js/faker

npx prisma init
```
selanjutnya kita setup babel  butuh file .babelrc

```
//.babelrc

{
    "presets": ["@babel/preset-env"]
}
```

```
//package.json

{
  "name": "express_sample_api",
  "version": "1.0.0",
  "description": "",
  "main": "/src/index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "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"
  }
}

```

```
//.env

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

```
//shema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model Notes{
  id          Int       @id @default(autoincrement())
  title       String    
  content     String
  author      String
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
}
```

```
//package.json

{
  "name": "express_sample_api",
  "version": "1.0.0",
  "description": "",
  "main": "/src/index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "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"
  }
}

```
selanjutnya kita push modelnya ke database

`npx prisma db push`

selanjutnya kita buat file connection 

```
//connection.js

import {PrismaClient} from "@prisma/client"
const db = new PrismaClient()

export default db
```
selanjutnya kita baut create dan read data

```
//note_controllers.js

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

//create note 
export const note_create = async (req=request, res= response)=>{
    try{
        const data = await req.body
        const createNote = await db.notes.create({
            data : {
                title : data.title,
                content : data.content,
                author : data.author,
            }
        })
        return res.status(201).json({
            success :true,
            data : createNote
        })
    }catch(error){
        return res.status(500).json({
            success : false,
            error : error.message
        })
    }
}

//read note
export const note_read = async (req=request, res=response)=>{
    try{
        const {page= 1, limit = 10}= await req.query
        const skip = (page-1)* limit
        const result = await db.notes.findMany({
            skip : skip,
            take : parseInt(limit)

        })

        const totalResult = await db.notes.count()
        return res.status(200).json({
            success : true,
            current_page : parseInt(page),
            total_page : Math.ceil(totalResult/limit),
            data : result
        })
    }catch(error){
        return res.status(500).json({
            success : false,
            error : error.message
        })
    }
}
```
selanjutnya kita ke routes

```
//note_routes

import express from 'express'
import { note_create, note_read } from '../controllers/note_controllers'

const note_routes = express.Router()

//create note
note_routes.post("/api/note/create", note_create)

//read note
note_routes.get("/api/notes/read", note_read)

export default note_routes
```

```
//index.js

import express from 'express'
import env from 'dotenv'
import note_routes from './routes/note_routes'
env.config()

//environtment variable
const {PORT} = process.env
const app=express()

//mdw
app.use(express.json())

//routes
app.use(note_routes)

//listener
app.listen(PORT, ()=>{
    console.info("server beckend berjalan...")
})
```

jalankan server 

`npm run dev`

![Image server berjalan](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hdnqdfmlsfm58d4rl7fn.png)

```
//note_routes

import express from 'express'
import { note_create, note_read } from '../controllers/note_controllers'

const note_routes = express.Router()

//create note
note_routes.post("/api/note/create", note_create)

//read note
note_routes.get("/api/notes/read", note_read)

export default note_routes
```
create data

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

read data di hit 

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

sekarang kita akan mneggunakan post man 

```
create new collection ganti namanya
add request NOTE CREATE
kita lanjut ke body
jangan lupa save, di body tulis

{
    "title": "ini title",
    "content": "ini content",
    "author": "andiismail"
}

```

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

add request lagi sekarang kita bikin untuk
read notesnya

![Image read postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gtp8khzx41grvtf4793k.png)

selanjutnya kita buat seedernya pakai data fakerjs

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

![Image paragraph](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zueb10hsrq6eovsvrrd.png)

```
//notes_seed.js

import {faker} from "@faker-js/faker"

const note_seed = ()=>{
    const fake_title = faker.definitions.title
    const fake_content = faker.lorem.paragraph()
    const fake_author = faker.internet.userName()

    console.log({fake_title, fake_content, fake_author})
}

note_seed()
```
selanjutnya buat pemanggil seedernya di package.json

```
//package.json

{
  "name": "express_sample_api",
  "version": "1.0.0",
  "description": "",
  "main": "/src/index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node ./src/index.js",
    "notes_seed": "babel-node ./src/seeds/notes_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"
  }
}

```

selanjutnya jalankan servernya 

`npm run notes_seed`

![Image tampil namanya](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4cwywct3p7nbaoqq1ql.png)


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

```
//notes_seed.js

import {faker} from "@faker-js/faker"
import db from "../../prisma/connection"
const note_seed = ()=>{
    const fake_title = faker.definitions.title
    const fake_content = faker.lorem.paragraph()
    const fake_author = faker.internet.userName()

    //console.log({fake_title, fake_content, fake_author})
    db.notes.create({
        data : {
            title : fake_title,
            content : fake_content,
            author : fake_author
        }
    })
        .then(res=>{
            console.info(`Dibuat notes dengan author ${fake_author}`)
        })
        .catch(err=>{console.error(err.message)})
}

//note_seed()
for (let i = 0; i<=100; i++){
    note_seed()
}
```
jalankan `npm run notes_seed`

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

sekarang kita jalanakn server 9000 
`npm run dev`

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

untuk mendapatkan data yang terbaru, kita tambahkan order by dari findMany() dan tambahkan juga total data.

```
//note_controllers.js

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

//create note 
export const note_create = async (req=request, res= response)=>{
    try{
        const data = await req.body
        const createNote = await db.notes.create({
            data : {
                title : data.title,
                content : data.content,
                author : data.author
            }
        })
        return res.status(201).json({
            success :true,
            data : createNote
        })
    }catch(error){
        return res.status(500).json({
            success : false,
            error : error.message
        })
    }
}

//read note
export const note_read = async (req=request, res=response)=>{
    try{
        const {page= 1, limit = 10}= await req.query
        const skip = (page-1)* limit
        const result = await db.notes.findMany({
            skip : skip,
            take : parseInt(limit),
            orderBy : {
                id :"desc" // a-z "desc"
            }
        })

        const totalResult = await db.notes.count()
        return res.status(200).json({
            success : true,
            current_page : parseInt(page),
            total_page : Math.ceil(totalResult/limit),
            total_data : totalResult,
            data : result
        })
    }catch(error){
        return res.status(500).json({
            success : false,
            error : error.message
        })
    }
}
```

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

![Image dsc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/837l8fwee3ijwntwz8z5.png)

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

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