-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDB_api.js
More file actions
355 lines (293 loc) · 10.7 KB
/
Copy pathDB_api.js
File metadata and controls
355 lines (293 loc) · 10.7 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
const express = require('express');
const { Customers, Products, Orders, Cart } = require("./DB_connection");
const { Sequelize, Op } = require("sequelize");
const cors = require('cors');
const app = express();
const PORT= 3000;
app.use(express.json());
app.use(cors());
app.get('/liveness', (req, res)=> {
res.status(200).send('OK');
});
// -------------- Products Routes ---------------
app.get('/products', async (req, res) => {
try {
//res.status(500).send('Internal Server Error - Simulated');
const products = await Products.findAll();
res.status(200).json(products);
} catch (error) {
console.error('Erreur lors de la récupération des produits:', error);
res.status(500).send('Internal Server Error');
}
});
//API TEST D'ERREUR
//-------------------------------------------------------------------------------------------
/*
app.get('/error', async (req, res) => {
try {
// Simuler une erreur en renvoyant une réponse avec un code d'erreur 500
res.status(500).send('Internal Server Error - Simulated');
} catch (error) {
console.error('Erreur lors de la récupération des produits:', error);
res.status(500).send('Internal Server Error');
}
});
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
*/
app.get('/products/:id', async (req, res) => {
const id = parseInt(req.params.id);
const product = await Products.findByPk(id);
if (product) {
res.status(200).json(product);
} else {
res.status(404).send(`Entity not found for id: ${id}`);
}
});
app.post('/products', async (req, res) => {
const { name, description, price, stockquantity } = req.body;
try {
// Créer un nouveau package dans la base de données
const prod = await Products.create({
name,
description,
price,
stockquantity
});
res.status(201).json(prod);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.put('/products/:id', async (req, res) => {
console.log('Received PUT request with body:', req.body);
const id = parseInt(req.params.id);
const newname = req.body.newname;
const newdescription = req.body.newdescription;
const newprice = req.body.newprice;
const newstock = req.body.newstock;
if (!newname ) {
res.status(400).json({ error: "A modification is required." });
return;
}
try {
const [rowsUpdated, [updateProduct]] = await Products.update(
{ name: newname, description: newdescription, price: newprice, stockquantity: newstock },
{
returning: true,
where: { productid: id },
}
);
if (rowsUpdated === 0 || !updateProduct) {
res.status(404).json({ error: 'Package not found' });
return;
}
res.status(200).json(updateProduct);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.delete('/products/:id', async (req, res) => {
const id = req.params.id;
try {
const result = await Products.destroy({
where: { productid: id }
});
if (result === 0) {
res.status(404).json({ success: false, message: 'No matching rows found for deletion.' });
return;
}
res.status(200).json({ success: true, message: 'Product deleted successfully', result });
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
// -------------- Orders Routes ----------------
app.post('/orders', async (req, res) => {
const { customerid, products } = req.body;
let total = 0;
try {
//Check productid
for (const item of products){
const product = await Products.findByPk(item.productid);
if (!product) {
return res.status(404).send(`Product not found with ID: ${item.productid}`);
}
//Compute the total price
total += product.price * item.quantity;
}
// Créer un nouvel order dans la base de données
const order = await Orders.create({
customerid: customerid,
products: products,
total_price: total
});
res.status(201).json(order);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/orders/:userId', async (req, res) => {
const userId = parseInt(req.params.userId);
try {
const orders = await Orders.findAll({
where: {
customerid: userId
},
});
if (orders && orders.length > 0) {
res.status(200).json(orders);
} else {
res.status(404).send(`No orders found for customerId: ${userId}`);
}
} catch (error) {
console.error('Error fetching orders:', error);
res.status(500).send('Internal Server Error');
}
});
// ---------------- Cart Routes -----------------
app.post('/cart/:userId', async (req, res) => {
const new_product = req.body.newproduct;
const customerid = parseInt(req.params.userId);
try {
// Récupérer le panier existant
let cart = await Cart.findOne({
where: {
customerid: customerid
},
});
//Check productid
const product = await Products.findByPk(new_product.productid);
if (!product) {
return res.status(404).send(`Product not found with ID: ${new_product.productid}`);
}
let totalc = 0;
let updatedProducts = [];
if (cart) {
// Si le panier existe, on récupère les produits sélectionnés
updatedProducts = cart.sel_product;
console.log(updatedProducts);
// Vérifier si le produit existe déjà dans le panier
const productIndex = updatedProducts.findIndex(p => p.productid === new_product.productid);
if (productIndex > -1) {
// Si le produit est déjà dans le cart, mettre à jour la quantité
updatedProducts[productIndex].quantity += new_product.quantity;
} else {
// Sinon, ajouter le nouveau produit
updatedProducts.push({ productid: new_product.productid, quantity: new_product.quantity });
}
console.log(updatedProducts);
// Recalculer le total
for (const sel_product of updatedProducts) {
const product = await Products.findByPk(sel_product.productid);
totalc += product.price * sel_product.quantity;
}
// Mettre à jour le panier existant
const newSelProduct = JSON.parse(JSON.stringify(updatedProducts)); // Crée une nouvelle instance de l'objet
cart = await Cart.update({
sel_product: newSelProduct,
total: totalc
},
{
returning: true,
where: { customerid: customerid },
}
);
} else {
// Si aucun panier n'existe, créer un nouveau panier
totalc = product.price * new_product.quantity;
updatedProducts.push({ productid: new_product.productid, quantity: new_product.quantity });
cart = await Cart.create({
customerid: customerid,
sel_product: updatedProducts,
total: totalc
});
}
res.status(201).json(cart);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/cart/:userId', async (req, res) => {
const userId = parseInt(req.params.userId);
try {
const cart = await Cart.findAll({
where: {
customerid: userId
},
});
if (cart && cart.length > 0) {
res.status(200).json(cart);
} else {
res.status(404).send(`No orders found for customerId: ${userId}`);
}
} catch (error) {
console.error('Error fetching orders:', error);
res.status(500).send('Internal Server Error');
}
});
app.delete('/cart/:userId/item/:productId', async (req, res) => {
const customerid = parseInt(req.params.userId);
const productid = parseInt(req.params.productId);
try {
// Récupérer le panier existant
let cart = await Cart.findOne({
where: {
customerid: customerid
},
});
if (!cart) {
return res.status(404).send(`Cart not found for customer ID: ${customerid}`);
}
let updatedProducts = cart.sel_product;
const productIndex = updatedProducts.findIndex(p => p.productid === productid);
console.log(productIndex);
if (productIndex > -1) {
// Si le produit est bien dans le cart, le supprimer
updatedProducts.splice(productIndex, 1);
} else {
return res.status(404).send(`Product not found in cart: ${productid}`);
}
// Si le panier est vide après la suppression, supprimez le panier
if (updatedProducts.length === 0) {
await Cart.destroy({
where: {
customerid: customerid
},
});
return res.status(200).send(`Cart for customer ID: ${customerid} has been deleted.`);
} else {
// Recalculer le total
let totalc = 0;
for (const sel_product of updatedProducts) {
const product = await Products.findByPk(sel_product.productid);
if (product) {
totalc += product.price * sel_product.quantity;
}
}
// Mettre à jour le panier
const newSelProduct = JSON.parse(JSON.stringify(updatedProducts)); // Crée une nouvelle instance de l'objet
cart = await Cart.update({
sel_product: newSelProduct,
total: totalc
},
{
returning: true,
where: { customerid: customerid },
}
);
}
res.status(201).json(cart);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});