fullstackopen-notes/parts/3/followAlong/index.js

95 lines
2 KiB
JavaScript
Raw Normal View History

2025-05-29 19:41:40 +02:00
const express = require("express");
const app = express();
2025-06-01 23:33:27 +02:00
const mongoose = require("mongoose");
const url = "mongodb://devroot:devroot@localhost:27017/fsopen?authSource=admin";
mongoose.set("strictQuery", false);
mongoose.connect(url);
const noteSchema = new mongoose.Schema({
content: String,
important: Boolean,
});
noteSchema.set("toJSON", {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
},
});
const Note = mongoose.model("Note", noteSchema);
2025-05-31 22:44:09 +02:00
app.use(express.json());
2025-05-29 19:41:40 +02:00
let notes = [
{ id: "1", content: "HTML is easy", important: true },
{ id: "2", content: "Browser can execute only JavaScript", important: false },
{
id: "3",
content: "GET and POST are the most important methods of HTTP protocol",
important: true,
},
];
2025-05-31 22:44:09 +02:00
const generateId = () => {
const maxId =
notes.length > 0 ? Math.max(...notes.map((n) => Number(n.id))) : 0;
return String(maxId + 1);
};
2025-05-29 19:41:40 +02:00
app.get("/", (request, response) => {
response.send("<h1>Hello World!</h1>");
});
app.get("/api/notes", (request, response) => {
2025-06-01 23:33:27 +02:00
Note.find({}).then((notes) => {
response.json(notes);
});
2025-05-29 19:41:40 +02:00
});
2025-05-31 22:44:09 +02:00
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);
});
2025-05-29 19:41:40 +02:00
app.get("/api/notes/:id", (request, response) => {
const id = request.params.id;
const note = notes.find((note) => note.id === id);
if (note) {
response.json(note);
} else {
response.status(404).end();
}
});
app.delete("/api/notes/:id", (request, response) => {
const id = request.params.id;
notes = notes.filter((note) => note.id !== id);
response.status(204).end();
});
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});