Express js Faker js node js
Published: 2022-12-11 11:41:42

```
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
![Image faker js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d2kc5uyrdf3c5ptk8qns.png)

![Image prisma](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yjdw8cnna6febpua5vv.png)

![Image express js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shsiyf7vw4pl1ql2u4nf.png)

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

```
npm i @babel/core @babel/node @babel/preset-env @faker-js/faker 
```

```
npx prisma init
code .
```

![Image file dan folder awal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m80lhi68g14c78o549jh.png)

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`

![Image cmd berhasil dijalankan](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2czy5p2i7itkfhj3lc50.png)

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

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.

![Image berhasil xcreate data user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twv5nsou758387ltlpuh.png)

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

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`

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

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

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

```

![Image hanya username](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xp4uh8he5r5f5sq01sl6.png)

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`

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

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

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