Pages

Sunday, 25 June 2023

CRUD WTIH EJS

Langkah Langkah :
1. Membuat koneksi kedatabse dengan sintak berikut ini :
const {Pool} = require('pg')

const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'songLabel',
    password: 'postgres',
    port: 5432,
    idleTimeoutMillis : 500
  })

//   cek koneksi
//   pool.query('SELECT NOW()', (err, result) => {
//     console.log(err, result);
//   })

module.exports = pool

2. Membuat migration untuk membuat tabel database


const pool = require("./config/connection");

let queryTableLabel = `create table "Labels" (
    "id" serial primary key,
    "name" varchar (120) not null,
    "since" date,
    "city" varchar (120) not null
);`

let queryTableSong = `create table "Songs" (
    "id" serial primary key,
    "title" varchar (100),
    "bandName" varchar (100),
    "duration" integer,
    "genre" varchar (10),
    "createdDate" date,
    "lyric" text,
    "imageUrl" varchar (150),
    "totalVote" integer,
    "LabelId" integer not null references "Labels" ("id")
);`

let dropTable = `DROP TABLE IF EXISTS "Labels", "Songs"`

pool.query(dropTable, (err, res) => {
    if(err){
        console.log(err, `EROR DROP TABLE`);
    }else{
        pool.query(queryTableLabel, (err, res) => {
            if(err){
                console.log(err, `EROR CREATE TABEL LABELS`);
            }else{
                console.log(`SUCCESS CREATE TABLE LABELS`);
                pool.query(queryTableSong, (err, res) => {
                    if(err){
                        console.log(`EROR CREATE TABEL SONGS`);
                    }else{
                        console.log(`SUCCESS CREATE TABLE SONGS`);
                    }
                })
            }
        })
    }
})

Pengembangan framework JavaScript, yang terdiri dari library kode JavaScript, memungkinkan developer menggunakan kode JS siap pakai dalam proyek mereka. Proses yang harus dilalui pun menjadi lebih cepat dan efisien karena mereka tidak perlu menulis kode dari nol.

Setiap framework JavaScript memiliki fitur yang berfungsi untuk menyederhanakan proses development dan debugging.


3. Membuat sedding untuk dapat melakukan insert data ke databse dari data json
const pool = require("./config/connection");
const fs = require('fs')

let label = fs.readFileSync("./data/labels.json", "utf-8")
label = JSON.parse(label)

let valueLabel = label.map(el => {
    return `('${el.name}', '${el.since}', '${el.city}')`
}).join(",")
let queryInsertLabel = `insert into "Labels" ("name", "since", "city")
values ${valueLabel};`

pool.query(queryInsertLabel, (err, result) => {
    if(err){
        console.log(err, 'EROR INSERT DATA LABELS');
    }else{
        console.log('SUCCESS INSERT DATA LABELS');
        let song = fs.readFileSync("./data/songs.json", "utf-8")
        song = JSON.parse(song)
        let valueSong = song.map(el => {
            return `('${el.title}', '${el.bandName}', ${el.duration}, '${el.genre}',
        '${el.createdDate}', '${el.lyric}', '${el.imageUrl}', ${el.totalVote}, ${el.LabelId})`
        }).join(",")

        let queryInsertSong = `insert into "Songs" ("title", "bandName", "duration",
        "genre", "createdDate", "lyric", "imageUrl", "totalVote", "LabelId")
        values ${valueSong}; `

        pool.query(queryInsertSong, (err, result) => {
            if(err){
                console.log(err, 'EROR INSERT DATA SONGS');
            }else{
                console.log('SUCCESS INSERT DATA SONGS');
            }
        })
    }
})

Meskipun Anda bisa menggunakan HTML dan CSS saja untuk membuat website, halaman yang dihasilkan hanya akan memiliki tampilan statis tanpa adanya JavaScript. Bahasa pemrograman ini memungkinkan pengunjung berinteraksi dengan halaman web, dan Anda pun bisa menyajikan user experience yang lebih baik.

4. Membuat class untuk model
const { fail } = require("assert")

class Label{
    constructor(id, name, since, city){
        this.id = id
        this.name = name
        this.since = since
        this.city = city
    }
    get sinceLocale(){
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        return this.since.toLocaleDateString('id-ID', options)
    }
}

class LabelDetailDuration extends Label{
    constructor(id, name, since, city, averageDuration, minDuration, maxDuration){
        super(id, name, since, city)
        this.averageDuration = +averageDuration
        this.minDuration = +minDuration
        this.maxDuration = +maxDuration
    }
}

class Song{
    constructor(id, title, bandName, duration, genre, totalVote){
        this.id = id
        this.title = title
        this.bandName = bandName
        this.duration = duration
        this.genre = genre
        this.totalVote = totalVote
    }
}

class SongDetail extends Song{
    constructor(id, title, bandName, duration, genre, totalVote, createdDate, lyric, imageUrl, LabelId, LabelName){
        super(id, title, bandName, duration, genre, totalVote)
        this.createdDate = createdDate
        this.lyric = lyric
        this.imageUrl = imageUrl
        this.LabelId = LabelId
        this.LabelName = LabelName
    }

    get dateCreate(){
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        return this.createdDate.toLocaleDateString('id-ID', options)
    }

    get inputDate() {
        const date = new Date(this.createdDate);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    };


class Factory{
    static createLabel(id, name, since, city){
        return new Label(id, name, since, city)
    }

    static createSong(id, title, bandName, duration, genre, totalVote){
        return new Song(id, title, bandName, duration, genre, totalVote)
    }

    static createLabelDetail(id, name, since, city, averageDuration, minDuration, maxDuration){
        return new LabelDetailDuration(id, name, since, city, averageDuration, minDuration, maxDuration)
    }

    static createSongDetail(id, title, bandName, duration, genre, totalVote, createdDate, lyric, imageUrl, LabelId, LabelName){
        return new SongDetail(id, title, bandName, duration, genre, totalVote, createdDate, lyric, imageUrl, LabelId, LabelName)
    }
}

module.exports = Factory




5. pada app.js untuk mengatur rute
// Happy coding guys
const express = require('express')
const pool = require('./config/connection')
const Factory = require('./models/class')
const app = express()
const port = 3000

app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false }))

app.get('/labels', (req, res) => {
    const queryLabels = `select * from "Labels"`
    pool.query(queryLabels, (err, result) => {
        if (err) {
            res.send(err)
        } else {
            result = result.rows.map(el => {
                return Factory.createLabel(el.id, el.name, el.since, el.city)
            })
            res.render('labels', { data: result })
        }
    })

})




app.get('/labels/detail', (req, res) => {
    let queryLabelDetail = `select l.*, max(s.duration) as max, min(s.duration) as min, cast(avg(s.duration)
                            as float) as avg from "Labels" l left join "Songs" s on s."LabelId" = l.id
                            group by l.id;`
    pool.query(queryLabelDetail, (err, result) => {
        if (err) {
            res.send(err)
        } else {
            // console.log(result);
            result = result.rows.map(el => {
                return Factory.createLabelDetail(el.id, el.name, el.since, el.city, el.avg, el.min, el.max)
            })
            res.render('label-details', { data: result })
        }
    })
})


app.get('/songs', (req, res) => {
    const {search} = req.query
    let querySongs = ``
    if(search){
        querySongs = `select * from "Songs" where "title" ilike '%${search}%'`
    }else{
        querySongs = `select * from "Songs" order by "totalVote" asc;`
    }
   
    pool.query(querySongs, (err, result) => {
        if (err) {
            res.send(err)
        } else {
            result = result.rows.map(el => {
                return Factory.createSong(el.id, el.title, el.bandName,
                el.duration, el.genre, el.totalVote)
            })
            res.render('songs', { data: result })
        }
    })
})


Dengan JavaScript, Anda juga bisa meningkatkan pengalaman browsing pengunjung menggunakan cookie. Untuk membuat, membaca, dan menghapus cookie dalam JavaScript, diperlukan properti document.cookie yang berfungsi sebagai “getter and setter” nilai cookie.

app.get('/songs/add', (req, res) => {
    let queryLabel = `select * from "Labels";`
    pool.query(queryLabel, (err, result) => {
        if (err) {
            res.render(err)
        } else {
            result = result.rows.map(el => {
                return Factory.createLabel(el.id, el.name, el.since, el.city)
            })
            res.render('add-song', { data: result })
        }
    })

})

app.post('/songs/add', (req, res) => {
    const { title, bandName, duration, genre, createDate, lyric, imageUrl, LabelId } = req.body
    let queryInsertSong = `
        insert into "Songs" ("title", "bandName", "duration", "genre", "createdDate", "lyric", "imageUrl", "totalVote", "LabelId")
        values ('${title}', '${bandName}', ${duration}, '${genre}', '${createDate}', '${lyric}', '${imageUrl}', 0, ${LabelId});`

    pool.query(queryInsertSong, (err, result) => {
        if(err){
            res.render(err)
        }else{
            res.redirect('/songs')
        }
    })
})


Menurut informasi dari website resmi Java, bahasa pemrograman JavaScript yang dikembangkan oleh Netscape, Inc. bukanlah bagian dari platform Java yang dikembangkan oleh Sun Microsystems (sebelum diakuisisi Oracle).

Perbedaan Java dan JavaScript adalah, Java merupakan bahasa pemrograman, sedangkan JavaScript merupakan skrip pemrograman. Kode JavaScript ditulis dalam teks dan bisa langsung diinterpretasikan browser, sedangkan Java harus di-compile menjadi bytecode yang bisa dipahami dan dijalankan komputer.


app.get('/songs/:id', (req, res) => {
    const idSong = req.params.id
    const queryById = `select s.*, l."name"  from "Songs" s join "Labels" l on l.id = s."LabelId"
    where s.id = ${idSong};`
    pool.query(queryById, (err, result) => {
        if(err){
            res.render(err)
        }else{
            result = result.rows.map(el => {
                return Factory.createSongDetail(el.id, el.title, el.bandName, el.duration, el.genre,
                el.totalVote, el.createdDate, el.lyric, el.imageUrl, el.LabelId, el.name)
            })
            // console.log(result);
            res.render('song-details', {data: result})
        }
    })
})

app.get('/songs/:id/vote', (req, res) => {
    const idSong = +req.params.id
    let queryVote = `update  "Songs" set "totalVote" = "totalVote" + 1 where id = ${idSong}`
    pool.query(queryVote, (err, result) => {
        if(err){
            res.render(err)
        }else{
            res.redirect(`/songs/${idSong}`)
        }
    })
})

app.get('/songs/:id/edit', (req, res) => {
    const idSong = +req.params.id
    let queryLabel = `select * from "Labels";`
    const querySong = `select s.*, l."name"  from "Songs" s join "Labels" l on l.id = s."LabelId" where s.id = ${idSong};`
    pool.query(queryLabel, (err, label) => {
        if (err) {
            res.render(err)
        } else {
            label = label.rows.map(el => {
                return Factory.createLabel(el.id, el.name, el.since, el.city)
            })
            pool.query(querySong, (err, song) => {
                if(err){
                    res.send(err)
                }else{
                    console.log(song);
                    song = song.rows.map(el => {
                        return Factory.createSongDetail(el.id, el.title, el.bandName, el.duration, el.genre,
                        el.totalVote, el.createdDate, el.lyric, el.imageUrl, el.LabelId, el.name)
                    })
                    res.render('edit-song', {label, song: song[0] })
                }
            })
        }
    })
})



Nah, bahasa scripting termasuk ke dalam bahasa pemrograman, tapi digunakan untuk memanipulasi, menyesuaikan, dan mengotomatiskan apa yang sudah ada di sistem. Sedangkan bahasa pemrograman biasanya digunakan untuk membuat program dari nol.

app.post('/songs/:id/edit', (req, res) => {
    const idSong = +req.params.id
    const {title, bandName, duration, genre, createDate, lyric, imageUrl, LabelId} = req.body
    const queryUpdateSong = `update "Songs" set
    "title" = '${title}',
    "bandName" = '${bandName}',
    "duration" = ${duration},
    "genre" = '${genre}',
    "createdDate" =  '${createDate}',
    "lyric" = '${lyric}',
    "imageUrl" = '${imageUrl}',
    "LabelId" = ${LabelId}
    where id = ${idSong};`

    pool.query(queryUpdateSong, (err, result) => {
        if(err){
            res.send(err)
        }else{
            res.redirect('/songs')
        }
    })
})

app.get('/songs/:id/delete', (req, res) => {
    const idSong = +req.params.id
    const queryDelete = `delete from "Songs" where id = ${idSong};`
    pool.query(queryDelete, (err, result) => {
        if(err){
            res.render(err)
        }else{
            res.redirect('/songs')
        }
    })
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

No comments:

Post a Comment