DEV Community

Cover image for Node js - cli app
Andi Ismail
Andi Ismail

Posted on

Node js - cli app

mkdir cli_app_2
cd cli_app_2
npm init
licensi MIT
Enter fullscreen mode Exit fullscreen mode

Image inquirer

npm install --save inquirer

Image prisma

npm install prisma
npx prisma init
Enter fullscreen mode Exit fullscreen mode

Image instalan awal

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

selanjutnya kita akan buat index.js

//index.js

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

jalankan aplikasi dengan mengetikkan npm start

Image cli2

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

berhasil menampilkan option login da register

Image cliappp2

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

hasilnya

Image exit

Image figma jam

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

Image if

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

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

npx prisma generate
npx prisma db push
npx prisma studio

Image prisma

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

selanjutnya kita buat file connection.js di prisma

//connection.js

import { PrismaClient } from "@prisma/client"

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

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

Image kakak

Image prisma kakak

prisma studio bisa tambah, edit dan hapus barang item

Image satu

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

Image dua

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

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

Image boby

Image prisma

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

Image vscode

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

Image tiga

Image boba

Terimakasih.

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

Top comments (0)