DEV Community

Cover image for Express postman
Andi Ismail
Andi Ismail

Posted on

Express postman

Image postman

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
Enter fullscreen mode Exit fullscreen mode

selanjutnya kita setup babel butuh file .babelrc

//.babelrc

{
    "presets": ["@babel/preset-env"]
}
Enter fullscreen mode Exit fullscreen mode
//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"
  }
}

Enter fullscreen mode Exit fullscreen mode
//.env

DATABASE_URL="file:./db.sqlite"
PORT=9000
Enter fullscreen mode Exit fullscreen mode
//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
}
Enter fullscreen mode Exit fullscreen mode
//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"
  }
}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
//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...")
})
Enter fullscreen mode Exit fullscreen mode

jalankan server

npm run dev

Image server berjalan

//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
Enter fullscreen mode Exit fullscreen mode

create data

Image create

read data di hit

Image read

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

Enter fullscreen mode Exit fullscreen mode

Image postman

add request lagi sekarang kita bikin untuk
read notesnya

Image read postman

selanjutnya kita buat seedernya pakai data fakerjs

Image fakerjs

Image paragraph

//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()
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

selanjutnya jalankan servernya

npm run notes_seed

Image tampil namanya

Image 1 data

//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()
}
Enter fullscreen mode Exit fullscreen mode

jalankan npm run notes_seed

Image berhasil 100nama

sekarang kita jalanakn server 9000
npm run dev

Image menampilkan 10 data

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
        })
    }
}
Enter fullscreen mode Exit fullscreen mode

Image pakai data terbaru

Image dsc

Image asc

github repo

Top comments (0)