Node js - cli app
Published: 2022-11-27 04:39:52

```
mkdir cli_app_2
cd cli_app_2
npm init
licensi MIT
```

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

`npm install --save inquirer`

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

```
npm install prisma
npx prisma init
```

![Image instalan awal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x82kcy6bnncj6p74iqlf.png)

tambahkan `type modul` dan `script start` sehingga kita bisa node start

```
//package.json

{
  "name": "cli_app_2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module", //tambahkan ini
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start":"node index.js" //dan ini
  },
  "author": "andiismail",
  "license": "MIT",
  "dependencies": {
    "inquirer": "^9.1.4",
    "prisma": "^4.6.1"
  }
}
```
selanjutnya kita akan buat index.js

```
//index.js

import inquirer from "inquirer";
console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)
```

jalankan aplikasi dengan mengetikkan `npm start`

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

selanjutnya kita gunakan prisma 

```
//index.js

import inquirer from "inquirer";
console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register"]
    }
])
.then((ans)=>{
    console.log(ans.option)
})
.catch((err)=>{
    console.error(err)
})
```
berhasil menampilkan option login da register

![Image cliappp2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vuf8sov0tzsc5hhh8bgc.gif)

agar tidak menggunakan kata ans ketika memunculkan option terus maka kita akan menjadikan option sebagai objek ans

```
//index.js

import inquirer from "inquirer";
console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register", "exit"]
    }
])
.then((ans)=>{
    //console.log(ans.option)
    const {option} = ans
    console.log(option)

})
.catch((err)=>{
    console.error(err)
})
```
hasilnya 

![Image exit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nlb4dheumlg43s2mwz5l.gif)


![Image figma jam](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vi1fp2od719iurtq0wws.png)

selanjutnya kita akan menggunakan pengkondisian 

```
//index.js

import inquirer from "inquirer";
console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register", "exit"]
    }
])
.then((ans)=>{
    
    //pengkondisian
    const {option} = ans
    
    //gunakan if
    if(option==="login"){
        console.clear()
        console.log("kamu memilih login")
        return
    }

    if(option==="register"){
        console.clear()
        console.log("kamu memilih register")
        return
    } 

    console.clear()
    console.log("terimakasih...")

})
.catch((err)=>{
    console.error(err)
})
```

![Image if](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myv5d4m72v8by55c0r94.gif)

selanjutnya kita akan buat function function yang kan memanggil console log yang telah kit buat sebelumnya.

`//function login 
function login (){
    console.clear()
    console.log("kamu memilih Login")
}

function resgister (){
    console.clear()
    console.log("kamu memilih Register")
}`

```
//index.js

import inquirer from "inquirer";
console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register", "exit"]
    }
])
.then((ans)=>{
    
    //destruct option objek dari ans
    const {option} = ans
    
    //gunakan if
    if(option==="login"){
        return login()
    }

    if(option==="register"){
        return resgister()
    } 

    exit()

})
.catch((err)=>{
    console.error(err)
})


//function login 
function login (){
    console.clear()
    console.log("kamu memilih Login")
}

function resgister (){
    console.clear()
    console.log("kamu memilih Register")
}

function exit (){
    console.clear()
    console.log("Terimakasih...")
}
```

hasilnya sama aja. selanjutnya kita akan buat database nya dengan prisma. 
kita ganti databse url di file .env

`DATABASE_URL="file:./db.sqlite"`

selanjutnya kita ke schema prisma

```
//schema.prisma

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model Users {
  //col name  type      option
  id          Int       @id @default(autoincrement())
  username    String    @unique
  password    String
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
}
```
`npx prisma generate
npx prisma db push
npx prisma studio`

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

```
//package.json

{
  "name": "cli_app_2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "andiismail",
  "license": "MIT",
  "dependencies": {
    "@prisma/client": "^4.6.1",
    "inquirer": "^9.1.4",
    "prisma": "^4.6.1"
  }
}
```

selanjutnya kita buat file connection.js di prisma 

```
//connection.js

import { PrismaClient } from "@prisma/client"

const db = new PrismaClient()
export default db
```
selanjutnya kita ke index.js

```
//index.js

import inquirer from "inquirer";
import db from "./prisma/connection.js"

console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register", "exit"]
    }
])
.then((ans)=>{
    
    //destruct option objek dari ans
    const {option} = ans
    
    //gunakan if
    if(option==="login"){
        return login()
    }

    if(option==="register"){
        return register()
    } 

    exit()

})
.catch((err)=>{
    console.error(err)
})

//function login
function login(){
    console.clear()
    console.log("kamu memilih login")
}

//function register
function register (){
    console.clear()
    //console.log("kamu memilih Login")

    //kita masukkan inquirer disini
    inquirer.prompt([
        {
            name : "username",
            message : "Masukkan username"
        },
        {
            name : "password",
            message : "Masukkan password",
            type : "password" 
        }
    ])
    .then((ans)=>{
        const {username, password} = ans

        //masukan data ke database
        db.users.create({
            data : {
                username : username,
                password : password
            }
        })
        .then((res)=>[
            console.log("data berhasil di simpan..")
        ])
        .catch((err)=>{
            console.error(err.message)
        })
    })
}

function exit (){
    console.clear()
    console.log("Terimakasih...")
}
```

![Image kakak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xjhm6ncevlvds5yfko8n.gif)

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

prisma studio bisa tambah, edit dan hapus barang item 

![Image satu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0n1sos6cgxi6hq3r8d16.gif)

permasalahan password kita belum di eskripsi kita bisa menggunaka bcrypt.js

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

`npm i bcryptjs`

kita buat folder baru namanya utils 

```
//hashPassword.js

import bcrypt from "bcryptjs"

/**
 * 
 * @param {string} password 
 * @returns 
 */
export function hashPassword(password){
    const salt = bcrypt.genSaltSync(10)
    const saltPassword = bcrypt.hashSync(password, salt)
    return saltPassword
}
```
kita import hashPassword.js ke index.js
`//masukan data ke database
        db.users.create({
            data : {
                username : username,
                password : hashPassword(password)
            }
        })`

```
//index.js

import inquirer from "inquirer";
import db from "./prisma/connection.js"
import {hashPassword} from './utils/hashPassword.js'

console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register", "exit"]
    }
])
.then((ans)=>{
    
    //destruct option objek dari ans
    const {option} = ans
    
    //gunakan if
    if(option==="login"){
        return login()
    }

    if(option==="register"){
        return register()
    } 

    exit()

})
.catch((err)=>{
    console.error(err)
})

//function login
function login(){
    console.clear()
    console.log("kamu memilih login")
}

//function register
function register (){
    console.clear()
    //console.log("kamu memilih Login")

    //kita masukkan inquirer disini
    inquirer.prompt([
        {
            name : "username",
            message : "Masukkan username"
        },
        {
            name : "password",
            message : "Masukkan password",
            type : "password" 
        }
    ])
    .then((ans)=>{
        const {username, password} = ans

        //masukan data ke database
        db.users.create({
            data : {
                username : username,
                password : hashPassword(password)
            }
        })
        .then((res)=>[
            console.log("data berhasil di simpan..")
        ])
        .catch((err)=>{
            console.error(err.message)
        })
    })
}

function exit (){
    console.clear()
    console.log("Terimakasih...")
}
```

![Image boby](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nkkju7fccnf5zqi80pxe.gif)

![Image prisma](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4miwsqx5t9yy5v2elqs.gif)

selesai register. selanjutnya kita akan buat login encrypt passwordnya. di hashPassword kita buat sebuah compare password karena passwordnya sudah berubah tidak seperti awal. 

```
//hashPassword.js

import bcrypt from "bcryptjs"

/**
 * 
 * @param {string} password 
 * @returns 
 */
export function hashPassword(password){
    const salt = bcrypt.genSaltSync(10)
    const saltPassword = bcrypt.hashSync(password, salt)
    return saltPassword
}

//compare password
/**
 * compare password dari databse
 * cara munculinnya garing bintang dua
 * @param {string} inputPassword 
 * @param {string} dbPassword 
 * @returns {boolean}
 */
export function comparePassword(inputPassword, dbPassword){
    return bcrypt.compareSync(inputPassword, dbPassword) //boolean
}
```

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

```
//index.js

import inquirer from "inquirer";
import db from "./prisma/connection.js"
import {hashPassword, comparePassword} from './utils/hashPassword.js'

console.clear()
console.log(`
===================================
APlikasi Cli 2
===================================
`)

//kasih pilhan mau login atau mau register 
inquirer.prompt([
    {
        name : "option",
        message : "silahkan pilih : ",
        type : "list",
        choices : ["login", "register", "exit"]
    }
])
.then((ans)=>{
    
    //destruct option objek dari ans
    const {option} = ans
    
    //gunakan if
    if(option==="login"){
        return login()
    }

    if(option==="register"){
        return register()
    } 

    exit()

})
.catch((err)=>{
    console.error(err)
})

//function login
function login(){
    console.clear()
    //console.log("kamu memilih login") //mulai dari sini
    inquirer.prompt([
        {
            name : 'username',
            message : 'masukan username'
        },
        {
            name : 'password',
            message : 'masukkan password : ',
            type : 'password'
        }
    ]) 
    .then(async(ans)=>{
        const {username, password} = ans
        const getUserData = await db.users.findUnique({
            where : {
                username : username
            }
        })

        //jika username tidak ditemukan
        if(!getUserData){
            return console.log("username tidak ditemukan")
        }

        //compare passwordnya
        const tryComparePassword = await comparePassword(password, getUserData.password)

        //jika password tidak seusai
        if(!tryComparePassword){
            return console.log("password salah..")
        }

        //semua sesuai 
        console.log(`
=====================================
SELAMAT DATANG ${getUserData.username}
=====================================
        `)

    })
}

//function register
function register (){
    console.clear()
    //console.log("kamu memilih Login")

    //kita masukkan inquirer disini
    inquirer.prompt([
        {
            name : "username",
            message : "Masukkan username"
        },
        {
            name : "password",
            message : "Masukkan password",
            type : "password" 
        }
    ])
    .then((ans)=>{
        const {username, password} = ans

        //masukan data ke database
        db.users.create({
            data : {
                username : username,
                password : hashPassword(password)
            }
        })
        .then((res)=>[
            console.log("data berhasil di simpan..")
        ])
        .catch((err)=>{
            console.error(err.message)
        })
    })
}

function exit (){
    console.clear()
    console.log("Terimakasih...")
}
```

![Image tiga](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xx531vyxmxtjqv269185.gif)

![Image boba](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5d0d3kd3496mznqvcz8d.png)

Terimakasih.

https://github.com/andiks2018/JvalleyNodejs-cliapp_2.git