followed along until exercise 3.1

This commit is contained in:
counterweight 2025-05-31 22:44:09 +02:00
parent ade19f00bc
commit 68aa0e9905
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
3 changed files with 36 additions and 0 deletions

View file

@ -1,6 +1,8 @@
const express = require("express"); const express = require("express");
const app = express(); const app = express();
app.use(express.json());
let notes = [ let notes = [
{ id: "1", content: "HTML is easy", important: true }, { id: "1", content: "HTML is easy", important: true },
{ id: "2", content: "Browser can execute only JavaScript", important: false }, { id: "2", content: "Browser can execute only JavaScript", important: false },
@ -11,6 +13,12 @@ let notes = [
}, },
]; ];
const generateId = () => {
const maxId =
notes.length > 0 ? Math.max(...notes.map((n) => Number(n.id))) : 0;
return String(maxId + 1);
};
app.get("/", (request, response) => { app.get("/", (request, response) => {
response.send("<h1>Hello World!</h1>"); response.send("<h1>Hello World!</h1>");
}); });
@ -19,6 +27,26 @@ app.get("/api/notes", (request, response) => {
response.json(notes); response.json(notes);
}); });
app.post("/api/notes", (request, response) => {
const body = request.body;
if (!body.content) {
return response.status(400).json({
error: "content missing",
});
}
const note = {
content: body.content,
important: body.important || false,
id: generateId(),
};
notes = notes.concat(note);
response.json(note);
});
app.get("/api/notes/:id", (request, response) => { app.get("/api/notes/:id", (request, response) => {
const id = request.params.id; const id = request.params.id;
const note = notes.find((note) => note.id === id); const note = notes.find((note) => note.id === id);

View file

@ -0,0 +1,7 @@
POST http://localhost:3001/api/notes
Content-Type: application/json
{
"content": "i'm a tttttnoty note",
"important": false
}

View file

@ -0,0 +1 @@
GET http://localhost:3001/api/notes