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
//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
read data di hit
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"
}
add request lagi sekarang kita bikin untuk
read notesnya
selanjutnya kita buat seedernya pakai data fakerjs
//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
//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
sekarang kita jalanakn server 9000
npm run dev
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
})
}
}
Top comments (0)