-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
105 lines (78 loc) · 2.48 KB
/
app.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
96
97
98
99
100
101
102
103
104
105
const express = require('express')
const app = express()
app.use(express.static("public"))
app.use(express.json())
idCounter = 0
products = []
app.get("/products", async function(request, response) {
// Respond with the products array
response.json(products)
console.log("/products was called!")
console.log(products)
})
app.get("/api/products", async function (request, response) {
response.json(products)
console.log("api/products was called!")
console.log(products)
})
app.get("/products/:id", async function(request, response) {
// NOTE: `params` accesses values from the URL path (:id)
var id = request.params.id
var productIndex = findProductIndexById(id)
// Respond with the specified product
response.json(products[productIndex])
console.log("/products/:id was called!")
console.log(products[productIndex])
})
app.post("/products", async function(request, response) {
// NOTE: `body` accesses values from the JSON request body
var providedName = request.body["name"]
var providedCategory = request.body["category"]
var providedPrice = request.body["price"]
var providedWeight = request.body["weight"]
var nextId = idCounter
idCounter = idCounter + 1
var newProduct = {
id: nextId,
name: providedName,
category: providedCategory,
price: providedPrice,
weight: providedWeight,
}
console.log(newProduct)
products.push(newProduct)
// Respond with the new product
response.json(newProduct)
console.log("/products was called!")
console.log(newProduct)
})
app.put("/products/:id", async function(request, response) {
// NOTE: `params` accesses values from the URL path (:id)
var id = request.params.id
var productIndex = findProductIndexById(id)
var newProduct = request.body;
products.splice(productIndex, 1, newProduct);
// Respond with the specified product
response.json({ msg: 'Updated product' })
console.log(products[productIndex])
})
app.delete("/products/:id", async function(request, response) {
// NOTE: `params` accesses values from the URL path
var id = request.params.id
var productIndex = findProductIndexById(id);
products.splice(productIndex, 1)
// Respond with a message
response.json({ msg: 'Deleted product' })
})
app.listen(3000, function() {
console.log("App listening on port 3000")
})
function findProductIndexById(id) {
for (var i = 0; i < products.length; i++) {
var product = products[i]
if (product["id"] == id) {
return i;
}
}
}
module.exports = app