-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.mjs
52 lines (40 loc) · 1.76 KB
/
app.mjs
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
//import manager from './ProductManager.mjs';
import { manager } from './ProductManager.mjs';
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
// Show all products
app.get('/api/products', async (req, res) => {
console.log("API get invoked.");
const products = await manager.getProducts();
const answer = products.length == 0 ? "No products available" : products;
res.status(manager.getLastStatus()).json(answer);
});
// Add a new product
app.post('/api/products', async (req, res) => {
console.log("API post invoked.");
const { name, description, category, amount } = req.body;
const answer = await manager.addProduct(name, description, category, amount) ||
`Product '${name}' with description '${description}' of category '${category}' has been added successfully with amount of '${amount || 0}'!`;
res.status(manager.getLastStatus()).json(answer);
});
// Update product amount
app.put('/api/products/:name', async (req, res) => {
console.log("API put invoked.");
const productName = req.params.name;
const newAmount = req.body.amount;
const answer = await manager.updateAmount(productName, newAmount) || `Product: '${productName}' amount has been updated successfully to '${newAmount}!'`;
res.status(manager.getLastStatus()).json(answer);
});
// Delete product
app.delete('/api/products/:name', async (req, res) => {
console.log("API delete invoked.");
const productName = req.params.name;
const answer = await manager.deleteProduct(productName) || `Product: '${productName} has been deleted successfully!`;
res.status(manager.getLastStatus()).json(answer);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});