-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.js
95 lines (89 loc) · 2.52 KB
/
admin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// attach data from the db
function displayProducts(product) {
let tableRow = document.createElement("tr")
tableRow.id = "table-row"
tableRow.innerHTML = `
<th scope="row">${product.id}</th>
<td>${product.title}</td>
<td>${product.description}</td>
<td>${product.image}</td>
<td>${product.price}</td>
<td><button class="btn" id="edit" style="background-color: orange;">Edit</button></td>
<td><button class="btn btn-light" style="background-color: red;" id="delete">Delete</button></td>
`
document.querySelector('#table-body').append(tableRow)
tableRow.querySelector('#edit').addEventListener('click', () => {
updatePrice(product.id)
})
tableRow.querySelector('#delete').addEventListener('click', () => {
tableRow.remove()
deleteRecord(product.id)
})
}
// fetching data from the db
// the endpoint here is products
let base_URL = 'http://localhost:3000'
function fetchProduct() {
fetch(`${base_URL}/products`)
.then((res) => res.json())
.then(products =>
products.forEach((product) => {
displayProducts(product)
}))
}
fetchProduct()
// function to collect the form data
//GET
let formData;
function collectFormData () {
let form = document.querySelector('#form')
form.addEventListener('submit', (e) => {
e.preventDefault()
formData = {
title: e.target.name.value,
image: e.target.name.value,
description: e.target.name.value
}
postProducts()
})
}
collectFormData();
// POST
//
function postProducts() {
fetch(`${base_URL}/products`, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(formData)
})
.then((res) => res.json())
.then(products => console.log(products))
}
// DELETE
// base_URL/products/id (Here we target the specific id rather than deleting everything)
function deleteRecord(id) {
fetch(`${base_URL}/products/${id}`, {
method: 'DELETE',
headers: {
"Content-Type": "apllication/json"
}
})
.then((res) => res.json())
.then(data => console.log(data))
}
// PATCH
//updating the product details
function updatePrice(id) {
fetch(`${base_URL}/products/${id}`, {
method: 'PATCH',
headers: {
"Content-Type": "apllication/json"
},
body: JSON.stringify({
price: 150000
})
})
.then((res) => res.json())
.then(data => console.log(data))}