Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (64 loc) · 1.59 KB
/
Copy pathserver.js
File metadata and controls
80 lines (64 loc) · 1.59 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
import express from "express";
function getNextId() {
const maxId = notes.reduce((max, note) => (note.id > max ? note.id : max), 0);
return maxId + 1;
}
const notes = [
{
id: 1,
title: "Nota 1",
content: "Contenido de la nota 1",
},
];
const app = express();
app.use(express.json());
const port = 3000;
app.get("/", (req, res) => {
res.json({
message: "Bienvenido a la API de notas",
version: "1.0",
endpoints: {
getNotes: "/notes",
createNote: "/notes",
deleteNote: "/notes/:id",
},
});
});
app.get("/notes", (req, res) => {
res.json(notes);
});
app.delete("/notes/:id", (req, res) => {
const noteId = parseInt(req.params.id);
const noteIndex = notes.findIndex((note) => note.id === noteId);
if (noteIndex === -1) {
return res.status(404).json({ message: "Nota no encontrada" });
}
notes.splice(noteIndex, 1);
res.status(204).send();
});
app.post("/notes", (req, res) => {
const newNote = {
id: getNextId(),
title: req.body.title,
content: req.body.content,
};
notes.push(newNote);
res.status(201).json(newNote);
});
app.patch("/notes/:id", (req, res) => {
const noteId = parseInt(req.params.id);
const note = notes.find((note) => note.id === noteId);
if (!note) {
return res.status(404).json({ message: "Nota no encontrada" });
}
if (req.body.title !== undefined) {
note.title = req.body.title;
}
if (req.body.content !== undefined) {
note.content = req.body.content;
}
res.json(note);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});