-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
105 lines (87 loc) · 2.35 KB
/
Copy pathindex.js
File metadata and controls
105 lines (87 loc) · 2.35 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
const express = require("express")
const app = express()
const bodyParser = require("body-parser")
const { readData,writeData } = require("./functions")
require("dotenv").config()
const port = process.env.PORT || 3000
//MIDLEWARE
app.use(bodyParser.json())
app.get("/", (req, res) => {
res.send("Welcome to my API with NodeJS")
})
app.get("/dishes", (req, res) => {
const data = readData()
res.json(data.dishes)
})
app.post("/dishes", (req, res) => {
const data = readData()
const dish = req.body
const newDish = {
id: data.dishes.length + 1,
...dish
}
data.dishes.push(newDish)
writeData(data)
res.json(newDish)
})
//EJERCICIO CREATE READ
app.get("/books/", (req, res) => {
const data = readData()
res.json(data.books)
})
app.post("/books", (req, res) => {
const data = readData()
const book = req.body
const newBook = {
id: data.books.length + 1,
...book
}
data.books.push(newBook)
writeData(data)
res.json(newBook)
})
// EJEMPLOS DE UPDATE Y DELETE
app.put("/dishes/:id", (req, res) => {
const data = readData()
const body = req.body
const id = parseInt(req.params.id)
const dishIndex = data.dishes.findIndex(dish => dish.id === id)
data.dishes[dishIndex] = {
id,
...body
}
writeData(data)
res.json({message: "Dish updated"})
})
app.delete("/dishes/:id", (req, res) => {
const data = readData()
const id = parseInt(req.params.id)
const dishIndex = data.dishes.findIndex(dish => dish.id === id)
data.dishes.splice(dishIndex, 1)
writeData(data)
res.json({message: "Dish deleted"})
})
//EJERCICIO UPDATE Y DELETE
app.put("/books/:id", (req, res) => {
const data = readData()
const body = req.body
const id = parseInt(req.params.id)
const bookIndex = data.books.findIndex(book => book.id === id)
data.books[bookIndex] = {
id,
...body
}
writeData(data)
res.json({message: "Book updated"})
})
app.delete("/books/:id", (req, res) => {
const data = readData()
const id = parseInt(req.params.id)
const bookIndex = data.books.findIndex(book => book.id === id)
data.books.splice(bookIndex, 1)
writeData(data)
res.json({message: "Book deleted"})
})
app.listen(port, () =>{
console.log(`Server running on port ${process.env.PORT}`)
})