Express js Faker js node js
Andi Ismail
Posted on December 11, 2022
mkdir express_faker
cd express_faker
npm init -y //agar jawab otomatis
`enter`
dot env agar kita dapat menggunakan file file yang ada di .env Faker akan mengenarete data faker tapi realistic
npm i @babel/core @babel/node @babel/preset-env @faker-js/faker
npx prisma init
code .
buat file .babelrc
//.babelrc
{
"presets": ["@babel/preset-env"]
}
lanjut package jso kita hapus "test" dan
//package.json
{
"name": "express_faker",
"version": "1.0.0",
"description": "",
"main": "./src/index.js",
"scripts": {
"dev": "nodemon --exec babel-node ./src/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.20.5",
"@babel/node": "^7.20.5",
"@babel/preset-env": "^7.20.2",
"@faker-js/faker": "^7.6.0",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"prisma": "^4.7.1"
}
}
selanjuntya kita buka env
//.env
DATABASE_URL="file:./db.sqlite"
PORT=9000
selanjutnya ke schema.prisma
//schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model Users {
id Int @id @default(autoincrement())
username String @unique
email String @unique
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
selanjutnya buat folder src > controllers || routes || seeds || index.js
npx prisma db push //ototmatis generate prisma client
selesai.
lanjut ke index.js
//index.js
import express from 'express'
import dotenv from 'dotenv'
import user_routes from './routes/user_routes'
dotenv.config()
const {PORT} =process.env
const app = express()
//middleware
app.use(express.json())
//buat route
app.use(user_routes)
// app.get("/api/users", (req, res)=>{
// res.send("berhasil konek...")
// })
//listener
app.listen(PORT, ()=>{
console.info("server berhasil dijalankan...")
})
npm run dev
buat file connection.js didalam folder prisma
//connection.js
import { PrismaClient } from "@prisma/client"
const db = new PrismaClient()
export default db
selanjutnya kita akan baut user_controller
//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()
return res.status(200).json({
success: true,
data : result
})
}catch(error){
return res.status(500).json({
success : false,
error : error.message
})
}
}
//user_routes
import express from "express";
import { user_create, user_read } from "../controllers/user_controller";
const user_routes = express.Router()
//route create user
user_routes.post("/api/user/create", user_create)
user_routes.get("/api/users/read", user_read)
export default user_routes
selanjutnya kita import ke index.js
//index.js
import express from 'express'
import dotenv from 'dotenv'
import user_routes from './routes/user_routes'
dotenv.config()
const {PORT} =process.env
const app = express()
//middleware
app.use(express.json())
//buat route
app.use(user_routes)
// app.get("/api/users", (req, res)=>{
// res.send("berhasil konek...")
// })
//listener
app.listen(PORT, ()=>{
console.info("server berhasil dijalankan...")
})
selanjutnya kita akan melakukan testing, yang kita gunakan adalah extension dari vs code dengan nama rest client, buat file tester.rest
//tester.rest
### create data siswa
POST http://localhost:9000/api/user/create
Content-Type: application/json
{
"username" : "andiismail",
"email" : "andi@andi.com",
"password" : "Jl H. Midi Limo Depok"
}
### read all user
GET http://localhost:9000/api/users/read
Content-Type: application/json
perhatikan untuk untuk email dan password gak boleh sama, karena di auniq sehingga hanya bisa ngehit sekali saja di send request, untuk yang kedua gunakan email dan password yang beda.
sekarang masuk ke pembahasan inti yaitu faker, dan disini kita butuh looping. Buat file users_seed.js di folder seeds
seeds.
//users_seed.js
import { faker } from "@faker-js/faker";
const fake_username = faker.name.fullName()
const fake_email = faker.internet.email()
const fake_password =faker.internet.password()
console.info({fake_username, fake_email, fake_password})
tambahkan di package.json
//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" //tambahkan yang ini
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.20.5",
"@babel/node": "^7.20.5",
"@babel/preset-env": "^7.20.2",
"@faker-js/faker": "^7.6.0",
"@prisma/client": "^4.7.1",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"prisma": "^4.7.1"
}
}
jalankan npm run users_seed
berhasil mengenerate data name, email dan password.
sekarangkita looping hanya username
//users_seed.js
import { faker } from "@faker-js/faker";
import db from "../../prisma/connection";
// const fake_username = faker.internet.userName()
// const fake_email = faker.internet.email()
// const fake_password =faker.internet.password()
// console.info({fake_username, fake_email, fake_password})
const users_seed = ()=>{
const fake_username = faker.internet.userName()
const fake_email = faker.internet.email()
const fake_password =faker.internet.password()
db.users.create({
data : {
username : fake_username,
email : fake_email,
password : fake_password
}
})
.then(res=>console.info(`username ${res.username} berhasil dibuat ...`))
.catch(err=>console.error(err.message))
}
users_seed()
buat looping untuk 100 username fake
//users_seed.js
import { faker } from "@faker-js/faker";
import db from "../../prisma/connection";
// const fake_username = faker.internet.userName()
// const fake_email = faker.internet.email()
// const fake_password =faker.internet.password()
// console.info({fake_username, fake_email, fake_password})
const users_seed = ()=>{
const fake_username = faker.internet.userName()
const fake_email = faker.internet.email()
const fake_password =faker.internet.password()
db.users.create({
data : {
username : fake_username,
email : fake_email,
password : fake_password
}
})
.then(res=>console.info(`username ${res.username} berhasil dibuat ...`))
.catch(err=>console.error(err.message))
}
// users_seed()
for (let i=0; i<100; i++){
users_seed()
}
sekarang hidupkan kembali server nodemonnya dengan
npm run dev
kalau kita read all user dengan hit send request maka akan terbaca 100 data.
Posted on December 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024