DEV Community

Cover image for Express js Faker js node js
Andi Ismail
Andi Ismail

Posted on

Express js Faker js node js

mkdir express_faker
cd express_faker
npm init -y //agar jawab otomatis
`enter`
Enter fullscreen mode Exit fullscreen mode

dot env agar kita dapat menggunakan file file yang ada di .env Faker akan mengenarete data faker tapi realistic
Image faker js

Image prisma

Image express js

Image dotenv

npm i @babel/core @babel/node @babel/preset-env @faker-js/faker 
Enter fullscreen mode Exit fullscreen mode
npx prisma init
code .
Enter fullscreen mode Exit fullscreen mode

Image file dan folder awal

buat file .babelrc

//.babelrc

{
    "presets": ["@babel/preset-env"]
}
Enter fullscreen mode Exit fullscreen mode

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

selanjuntya kita buka env

//.env

DATABASE_URL="file:./db.sqlite"
PORT=9000
Enter fullscreen mode Exit fullscreen mode

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

selanjutnya buat folder src > controllers || routes || seeds || index.js

npx prisma db push //ototmatis generate prisma client
Enter fullscreen mode Exit fullscreen mode

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

npm run dev

Image cmd berhasil dijalankan

Image berhasil koneksi

buat file connection.js didalam folder prisma

//connection.js

import { PrismaClient } from "@prisma/client"

const db = new PrismaClient()
export default db
Enter fullscreen mode Exit fullscreen mode

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

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

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

Enter fullscreen mode Exit fullscreen mode

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

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.

Image berhasil xcreate data user

Image read all user

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

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

Enter fullscreen mode Exit fullscreen mode

jalankan npm run users_seed

Image data 1

Image data 2

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()

Enter fullscreen mode Exit fullscreen mode

Image hanya username

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

sekarang hidupkan kembali server nodemonnya dengan

npm run dev

Image 100 uername

kalau kita read all user dengan hit send request maka akan terbaca 100 data.

github repo

Top comments (0)