Selamün Aleyküm,
Javascript çalışmaların sırasında tecrübe ettiğim çalışmayı buradan paylaşmak istedim.
Amaç : localde bulunan bir json server üzerinde CRUD örneği yapmak ve webpack kullanımı.
Not: bazı js ve css leri yerel çalıştırmak istemiştim. webpack ile bundle edeyim dedim. Tüm css, scss ve js dosyalarını bundle.js içinde topladı. css classlarının js içinde çalışabildiğini buradan öğrendim ama webpack uyarı verdi performans kaybı yaşanabilir diye js dosyası 504 kb olmuş ayrıca kendisi 999.bundle.js diye bir dosya daha oluşturup ana js dosyasına bağlamış. Şimdi bazı js ve css,scss dosyalarını dışadan ekledim. tekrar bundle ettiğimde yine 999 isimli js dosyası oluşuyor. Neden oluyor bilemedim. Neyse örneğin github linki aşağıdadır.
github linki
Hızlı incelemek isteyen için js kodları aşağıdadır.
src => index.js
import './js/main';
src=> js => request.js
export class Request {
constructor(url) {
this.url = "http://localhost:3000/employees";
}
async get(){
return (await fetch(this.url)).json();
}
async post(data){
return (await fetch(this.url,{
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type":"application/json; charset=UTF-8"
}
}));
}
async put(id,data){
return (await fetch(this.url + "/" + id,{
method: 'PUT',
body: JSON.stringify(data),
headers: {
"Content-type":"application/json; charset=UTF-8"
}
}));
}
async delete(id){
return (await fetch(this.url + "/" + id,{
method: 'DELETE',
}));
}
}
src=> js => main.js
import {Request} from "./request";
import {UI} from "./ui";
const employeeForm = document.getElementById("employeeFrom");
const employeesTable = document.getElementById("employeesTable");
const req = new Request();
const ui = new UI();
document.addEventListener('DOMContentLoaded', function () {
req.get()
.then(response => ui.pushDataToUI(response))
.catch(err => ui.showAlert(err));
});
employeeForm.addEventListener("submit",function (e){
const data = {
name : employeeForm.elements["name"].value,
department : employeeForm.elements["department"].value,
salary : Number(employeeForm.elements["salary"].value)
}
req.post(data).then(status => {
ui.showAlert(status);
ui.pushCreatedDataToUI(data);
employeeForm.elements["name"].value = "";
employeeForm.elements["department"].value = "";
employeeForm.elements["salary"].value = "";
}).catch(status => ui.showAlert(status));
e.preventDefault();
});
employeesTable.addEventListener("click",function (e){
const employeeId = e.target.parentElement.parentElement.firstChild.textContent;
const row = e.target.parentElement.parentElement;
switch (e.target.name){
case "deleteButton":
req.delete(employeeId).then(status => {
ui.showAlert(status);
ui.removeDataFromUI(row);
}).catch(status => ui.showAlert(status));
break;
case "editButton":
ui.prepareUiForUpdateData(row);
break;
case "cancelButton":
ui.cancelUpdateProcessUI(e);
break;
case "updateButton":
const updateForm = document.getElementById("updateForm");
updateForm.addEventListener("submit",function (e){
const id = updateForm.elements["idUPD"].value;
const dataUPD = {
name : updateForm.elements["nameUPD"].value,
department : updateForm.elements["departmentUPD"].value,
salary : Number(updateForm.elements["salaryUPD"].value)
}
req.put(id,dataUPD)
.then(status => {
ui.updateUIAfterUpdateDatabase(e,dataUPD);
ui.showAlert(status);
})
.catch(err => console.error(err));
e.preventDefault();
});
break;
}
});
src=> js => ui.js
export class UI {
constructor() {
this.employeesTable = document.getElementById("employeesTable");
}
pushDataToUI(response){
response.forEach(value => {
this.employeesTable.innerHTML += '<tr><th scope="row">'+value.id+'</th><td>'+value.name+'</td><td>'+value.department+'</td><td>'+value.salary+'</td>' +
'<td>' +
'<button name="editButton" class="btn-success btn btn-sm">Düzenle</button>'+
'<button name="deleteButton" class="btn-danger btn btn-sm ms-2">Delete</button>'+
'</td>' +
'</tr>';
});
}
pushCreatedDataToUI(data){
let newId;
if(this.employeesTable.innerHTML === ""){
newId = 1;
}else{
newId = Number(this.employeesTable.lastElementChild.firstChild.textContent) + 1;
}
this.employeesTable.innerHTML += '<tr><th scope="row">'+ newId + '</th><td>'+data.name+'</td><td>'+data.department+'</td><td>'+data.salary+'</td>' +
'<td>' +
'<button name="editButton" class="btn-success btn btn-sm">Düzenle</button>'+
'<button name="deleteButton" class="btn-danger btn btn-sm ms-2">Delete</button>'+
'</td>' +
'</tr>';
}
removeDataFromUI(row){
row.remove();
}
prepareUiForUpdateData(row){
row.style.display = "none";
const id = row.children[0].textContent;
const name = row.children[1].textContent;
const department = row.children[2].textContent;
const salary = row.children[3].textContent;
let newRow = document.createElement("tr");
let newCol = document.createElement("td");
newCol.setAttribute("colspan","5");
newCol.innerHTML = '<form id="updateForm"><div class="input-group input-group-sm">' +
'<input name="idUPD" type="hidden" class="form-control" value="' + id + '">' +
'<input name="nameUPD" type="text" class="form-control" value="' + name + '">' +
'<input name="departmentUPD" type="text" class="form-control" value="' + department + '">' +
'<input name="salaryUPD" type="number" class="form-control" value="' + salary + '">' +
'<button type="submit" name="updateButton" class="btn btn-sm btn-primary">Güncelle</button>' +
'<button type="button" name="cancelButton" class="btn btn-sm btn-danger">Vazgeç</button>' +
'</div></form>';
newRow.appendChild(newCol);
row.parentElement.insertBefore(newRow,row.nextElementSibling);
}
updateUIAfterUpdateDatabase(e,data){
const updateInputs = e.target.parentElement.parentElement;
const originalData = e.target.parentElement.parentElement.previousElementSibling;
updateInputs.remove();
originalData.style.display = "";
originalData.children[1].textContent = data.name
originalData.children[2].textContent = data.department
originalData.children[3].textContent = data.salary
}
cancelUpdateProcessUI(e){
const previousTrElement = e.target.parentElement.parentElement.parentElement.parentElement;
const hiddenTrElement = e.target.parentElement.parentElement.parentElement.parentElement.previousElementSibling;
hiddenTrElement.style.display = "";
previousTrElement.remove();
}
showAlert(status){
switch (status.status){
case 200:
case 201:
case 204:
console.log("Process Success");
break;
case 404:
console.error("Process Failed, status code : ", status.status)
break;
}
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: ["@babel/polyfill",'./src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
mode: "production",
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ["@babel/preset-env"]
}
}
}
]
},
devServer: {
port: 3200,
index: 'index.html'
}
};
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Çalışanlar Uygulaması</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-4">
<div class="p-2 rounded mt-2 bg-light border">
<h4 class="text-center"><i class="fas fa-user-plus"></i> Çalışanlar Projesi</h4>
</div>
<form id="employeeFrom">
<input name="name" type="text" class="form-control mt-2" placeholder="Çalışan İsmi">
<input name="department" type="text" class="form-control mt-2" placeholder="Departman">
<input name="salary" type="number" step="1" class="form-control mt-2" placeholder="Maaş">
<div class="mt-2 d-flex justify-content-end">
<button class="btn btn-danger btn-sm fw-bold"><i class="fas fa-save"></i> Kaydet</button>
</div>
</form>
</div>
<div class="col-lg-8">
<div class="p-2 rounded mt-2 bg-light border">
<h4 class="text-center"><i class="fas fa-user-circle"></i> Çalışanlar</h4>
</div>
<table class="table table-striped table-sm text-center">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">İsim</th>
<th scope="col">Departman</th>
<th scope="col">Maaş</th>
<th scope="col">İşlem</th>
</tr>
</thead>
<tbody id="employeesTable"></tbody>
</table>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="./dist/bundle.js"></script>
</body>
</html>