From fa48a58d41cf2e9f57099f507b665e8ded36616e Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 28 May 2025 12:21:32 +0200 Subject: [PATCH 01/28] install packages --- package.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index bf25bb6..44cce74 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,9 @@ "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", + "dotenv": "^16.5.0", "express": "^4.17.3", - "nodemon": "^3.0.1" + "express-list-endpoints": "^7.1.1", + "nodemon": "^3.1.10" } } From b11e5994d64ddb19860d71eca5212a90fd3975ad Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 28 May 2025 13:48:30 +0200 Subject: [PATCH 02/28] creating endpoint to find specific thought --- data.json | 10 +++++----- server.js | 25 ++++++++++++++++++++++++- todo.md | 8 ++++++++ 3 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 todo.md diff --git a/data.json b/data.json index a2c844f..62b0fd7 100644 --- a/data.json +++ b/data.json @@ -1,5 +1,5 @@ [ - { + { "_id": "682bab8c12155b00101732ce", "message": "Berlin baby", "hearts": 37, @@ -7,7 +7,7 @@ "__v": 0 }, { - "_id": "682e53cc4fddf50010bbe739", + "_id": "682e53cc4fddf50010bbe739", "message": "My family!", "hearts": 0, "createdAt": "2025-05-22T22:29:32.232Z", @@ -25,7 +25,7 @@ "message": "Newly washed bedlinen, kids that sleeps through the night.. FINGERS CROSSED đŸ€žđŸŒ\n", "hearts": 6, "createdAt": "2025-05-21T21:42:23.862Z", - "__v": 0 + "__v": 0 }, { "_id": "682e45804fddf50010bbe736", @@ -53,7 +53,7 @@ "message": "A god joke: \nWhy did the scarecrow win an award?\nBecause he was outstanding in his field!", "hearts": 12, "createdAt": "2025-05-20T20:54:51.082Z", - "__v": 0 + "__v": 0 }, { "_id": "682cebbe17487d0010a298b5", @@ -74,7 +74,7 @@ "message": "Summer is coming...", "hearts": 2, "createdAt": "2025-05-20T15:03:22.379Z", - "__v": 0 + "__v": 0 }, { "_id": "682c706c951f7a0017130024", diff --git a/server.js b/server.js index f47771b..a0396ff 100644 --- a/server.js +++ b/server.js @@ -1,5 +1,7 @@ import cors from "cors" import express from "express" +import listEndpoints from "express-list-endpoints" +import thoughtsData from "./data.json" // Defines the port the app will run on. Defaults to 8080, but can be overridden // when starting the server. Example command to overwrite PORT env variable value: @@ -13,8 +15,29 @@ app.use(express.json()) // Start defining your routes here app.get("/", (req, res) => { - res.send("Hello Technigo!") + const endpoints = listEndpoints(app) + res.json({ + message: "Welcome to the Happy Thoughts API", + endpoints: endpoints + }) }) +//endpoint for getting all thoughts +app.get("/thoughts", (req, res) => { + res.json(thoughtsData) +}) + +//endpoint for getting one thought +app.get("/thoughts/:id", (req, res) => { + console.log(typeof req.params.id) + const thought = thoughtsData.find(thought => thought._id === req.params.id) + + if (!thought) { + return res.status(404).json({ error: "Thought not found" }) + } + res.json(thought) +}) + + // Start the server app.listen(port, () => { diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..0d55214 --- /dev/null +++ b/todo.md @@ -0,0 +1,8 @@ +-Your API should have at least three (for now) routes. Try to push yourself to do more, though! + +-A minimum of one endpoint to return a collection of results (an array of elements). + +-A minimum of one endpoint to return a single result (single element). + +-Your API should be RESTful +-You should follow the guidelines on how to write clean code. \ No newline at end of file From 094078af4047af99fe0aacdcd10094579f2b724a Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 28 May 2025 16:19:50 +0200 Subject: [PATCH 03/28] create an endpoint to serch for different amounts of likes --- server.js | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/server.js b/server.js index a0396ff..26b59e0 100644 --- a/server.js +++ b/server.js @@ -3,6 +3,9 @@ import express from "express" import listEndpoints from "express-list-endpoints" import thoughtsData from "./data.json" +//variable to not modify the original data +let thoughts = [...thoughtsData] + // Defines the port the app will run on. Defaults to 8080, but can be overridden // when starting the server. Example command to overwrite PORT env variable value: // PORT=9000 npm start @@ -21,15 +24,27 @@ app.get("/", (req, res) => { endpoints: endpoints }) }) + + + //endpoint for getting all thoughts app.get("/thoughts", (req, res) => { - res.json(thoughtsData) + + let filteredThoughts = thoughts + + //show hearts with more than 0 likes + if (req.query.minHearts !== undefined) { + const minHearts = +req.query.minHearts + filteredThoughts = filteredThoughts.filter(thought => thought.hearts > minHearts) + } + + res.json(filteredThoughts) }) //endpoint for getting one thought app.get("/thoughts/:id", (req, res) => { - console.log(typeof req.params.id) - const thought = thoughtsData.find(thought => thought._id === req.params.id) + + const thought = thoughts.find(thought => thought._id === req.params.id) if (!thought) { return res.status(404).json({ error: "Thought not found" }) @@ -38,6 +53,19 @@ app.get("/thoughts/:id", (req, res) => { }) +//endpoint for deleting a thought +//returns -1 if thought doesnt exist +app.delete("/thoughts/:id", (req, res) => { + const index = thoughts.findIndex(thought => thought._id === req.params.id) + + if (index == -1) { + return res.status(404).json({ error: "thought dosnt exist" }) + } + + const deletedThought = thoughts.splice(index, 1)[0] + res.json({ message: "Thought deleted", deletedThought }) +}) + // Start the server app.listen(port, () => { From a09e7b823b679b34d5cae68c59ddca4437315c49 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 28 May 2025 16:21:10 +0200 Subject: [PATCH 04/28] cleanup --- package.json | 2 +- todo.md | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/package.json b/package.json index 44cce74..9b28baf 100644 --- a/package.json +++ b/package.json @@ -18,4 +18,4 @@ "express-list-endpoints": "^7.1.1", "nodemon": "^3.1.10" } -} +} \ No newline at end of file diff --git a/todo.md b/todo.md index 0d55214..e69de29 100644 --- a/todo.md +++ b/todo.md @@ -1,8 +0,0 @@ --Your API should have at least three (for now) routes. Try to push yourself to do more, though! - --A minimum of one endpoint to return a collection of results (an array of elements). - --A minimum of one endpoint to return a single result (single element). - --Your API should be RESTful --You should follow the guidelines on how to write clean code. \ No newline at end of file From ba24a8ec4b9495910d2aaf1a00c23e3d98f7739a Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 2 Jun 2025 13:11:50 +0200 Subject: [PATCH 05/28] install mongoose and start using --- package.json | 3 ++- server.js | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 9b28baf..9c9d350 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "dotenv": "^16.5.0", "express": "^4.17.3", "express-list-endpoints": "^7.1.1", + "mongoose": "^8.15.1", "nodemon": "^3.1.10" } -} \ No newline at end of file +} diff --git a/server.js b/server.js index 26b59e0..11efae5 100644 --- a/server.js +++ b/server.js @@ -2,6 +2,7 @@ import cors from "cors" import express from "express" import listEndpoints from "express-list-endpoints" import thoughtsData from "./data.json" +import mongoose from "mongoose" //variable to not modify the original data let thoughts = [...thoughtsData] @@ -16,6 +17,12 @@ const app = express() app.use(cors()) app.use(express.json()) +const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/thoughts" +mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }) +mongoose.Promise = Promise +//FortsĂ€tt hĂ€r och Ă€ndra local host namn sen + + // Start defining your routes here app.get("/", (req, res) => { const endpoints = listEndpoints(app) From 0e33a1a0f9fed6f46d2023d39718c3b10463d0c1 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 4 Jun 2025 16:40:48 +0200 Subject: [PATCH 06/28] new import --- server.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index 11efae5..a46fd81 100644 --- a/server.js +++ b/server.js @@ -1,8 +1,12 @@ import cors from "cors" import express from "express" import listEndpoints from "express-list-endpoints" -import thoughtsData from "./data.json" import mongoose from "mongoose" +import dotenv from "dotenv" + +import thoughtsData from "./data.json" + +dotenv.config() //variable to not modify the original data let thoughts = [...thoughtsData] From 53f890dcad4fa652b9c1d83ec0fbfc81082ef6ac Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Thu, 5 Jun 2025 13:07:59 +0200 Subject: [PATCH 07/28] add a delete thought endpoint --- server.js | 172 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 143 insertions(+), 29 deletions(-) diff --git a/server.js b/server.js index a46fd81..36dcec3 100644 --- a/server.js +++ b/server.js @@ -4,12 +4,12 @@ import listEndpoints from "express-list-endpoints" import mongoose from "mongoose" import dotenv from "dotenv" -import thoughtsData from "./data.json" +// import thoughtsData from "./data.json" -dotenv.config() +dotenv.config() -//variable to not modify the original data -let thoughts = [...thoughtsData] +const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/thoughts" +mongoose.connect(mongoUrl) // Defines the port the app will run on. Defaults to 8080, but can be overridden // when starting the server. Example command to overwrite PORT env variable value: @@ -21,10 +21,29 @@ const app = express() app.use(cors()) app.use(express.json()) -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/thoughts" -mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }) -mongoose.Promise = Promise -//FortsĂ€tt hĂ€r och Ă€ndra local host namn sen + + +const thoughtSchema = new mongoose.Schema({ + _id: String, + message: String, + hearts: Number, + createdAt: { + type: Date, + default: Date.now() + } +}) +//HĂ€r lĂ€gg +const Thought = mongoose.model("Thought", thoughtSchema) + +// if (process.env.RESET_DB) { +// const seedDatabase = async () => { +// await Thought.deleteMany({}) +// thoughtsData.forEach(thought => { +// new Thought(thought).save() +// }) +// } +// seedDatabase() +// } // Start defining your routes here @@ -38,45 +57,140 @@ app.get("/", (req, res) => { -//endpoint for getting all thoughts -app.get("/thoughts", (req, res) => { +//endpoint for getting all thoughts +app.get("/thoughts", async (req, res) => { + const { likes, minLikes } = req.query + + const query = {} + + //Make sure there is error handelning when parameter is not a number - let filteredThoughts = thoughts + if (likes !== undefined) { + const numLikes = +likes + if (isNaN(numLikes)) { + return res.status(400).json({ error: "Query parameter 'likes' must be a number." }) + } + query.hearts = numLikes + } - //show hearts with more than 0 likes - if (req.query.minHearts !== undefined) { - const minHearts = +req.query.minHearts - filteredThoughts = filteredThoughts.filter(thought => thought.hearts > minHearts) + if (minLikes !== undefined) { + const numMinLikes = +minLikes + if (isNaN(numMinLikes)) { + return res.status(400).json({ error: "Query parameter 'likes' must be a number." }) + } + query.hearts = { $gte: numMinLikes } } - res.json(filteredThoughts) + try { + const filteredThoughts = await Thought.find(query) + + if (filteredThoughts.length === 0) { + return res.status(404).json({ + success: false, + response: [], + message: "No thougth found for that query. Please try another one" + }) + } + res.status(200).json({ + success: true, + response: filteredThoughts + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server error! Failed to fetch thoughts." + }) + } }) -//endpoint for getting one thought -app.get("/thoughts/:id", (req, res) => { +// endpoint for getting one thought - const thought = thoughts.find(thought => thought._id === req.params.id) +app.get("/thoughts/:id", async (req, res) => { + const { id } = req.params - if (!thought) { - return res.status(404).json({ error: "Thought not found" }) + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Invalid id" + }) + } + + try { + const thought = await Thought.findById(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: [], + message: "No thougth found" + }) + } + + res.status(200).json({ + success: true, + response: thought + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server error! Failed to fetch thoughts." + }) } - res.json(thought) }) //endpoint for deleting a thought -//returns -1 if thought doesnt exist -app.delete("/thoughts/:id", (req, res) => { - const index = thoughts.findIndex(thought => thought._id === req.params.id) - if (index == -1) { - return res.status(404).json({ error: "thought dosnt exist" }) +app.delete("/thoughts/:id", async (req, res) => { + const { id } = req.params + + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Could not delete! Invalid id" + }) } - const deletedThought = thoughts.splice(index, 1)[0] - res.json({ message: "Thought deleted", deletedThought }) + try { + const thought = await Thought.findByIdAndDelete(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: [], + message: "No thougth found" + }) + } + + res.status(200).json({ + success: true, + response: thought, + message: "Was successfully deleted" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server error! Failed to fetch thoughts." + }) + } }) +// app.delete("/thoughts/:id", (req, res) => { +// const index = thoughts.findIndex(thought => thought._id === req.params.id) + +// if (index == -1) { +// return res.status(404).json({ error: "thought dosnt exist" }) +// } + +// const deletedThought = thoughts.splice(index, 1)[0] +// res.json({ message: "Thought deleted", deletedThought }) +// }) + // Start the server app.listen(port, () => { From 03dc5a75f4c5d880768b9d2e3f9717b391f550b0 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Thu, 5 Jun 2025 17:33:00 +0200 Subject: [PATCH 08/28] add a post --- data.json | 17 ---------------- server.js | 58 +++++++++++++++++++++++++++---------------------------- 2 files changed, 29 insertions(+), 46 deletions(-) diff --git a/data.json b/data.json index 62b0fd7..be839a2 100644 --- a/data.json +++ b/data.json @@ -1,118 +1,101 @@ [ { - "_id": "682bab8c12155b00101732ce", "message": "Berlin baby", "hearts": 37, "createdAt": "2025-05-19T22:07:08.999Z", "__v": 0 }, { - "_id": "682e53cc4fddf50010bbe739", "message": "My family!", "hearts": 0, "createdAt": "2025-05-22T22:29:32.232Z", "__v": 0 }, { - "_id": "682e4f844fddf50010bbe738", "message": "The smell of coffee in the morning....", "hearts": 23, "createdAt": "2025-05-22T22:11:16.075Z", "__v": 0 }, { - "_id": "682e48bf4fddf50010bbe737", "message": "Newly washed bedlinen, kids that sleeps through the night.. FINGERS CROSSED đŸ€žđŸŒ\n", "hearts": 6, "createdAt": "2025-05-21T21:42:23.862Z", "__v": 0 }, { - "_id": "682e45804fddf50010bbe736", "message": "I am happy that I feel healthy and have energy again", "hearts": 13, "createdAt": "2025-05-21T21:28:32.196Z", "__v": 0 }, { - "_id": "682e23fecf615800105107aa", "message": "cold beer", "hearts": 2, "createdAt": "2025-05-21T19:05:34.113Z", "__v": 0 }, { - "_id": "682e22aecf615800105107a9", "message": "My friend is visiting this weekend! <3", "hearts": 6, "createdAt": "2025-05-21T18:59:58.121Z", "__v": 0 }, { - "_id": "682cec1b17487d0010a298b6", "message": "A god joke: \nWhy did the scarecrow win an award?\nBecause he was outstanding in his field!", "hearts": 12, "createdAt": "2025-05-20T20:54:51.082Z", "__v": 0 }, { - "_id": "682cebbe17487d0010a298b5", "message": "Tacos and tequila🌼đŸč", "hearts": 2, "createdAt": "2025-05-19T20:53:18.899Z", "__v": 0 }, { - "_id": "682ceb5617487d0010a298b4", "message": "Netflix and late night ice-cream🍩", "hearts": 1, "createdAt": "2025-05-18T20:51:34.494Z", "__v": 0 }, { - "_id": "682c99ba3bff2d0010f5d44e", "message": "Summer is coming...", "hearts": 2, "createdAt": "2025-05-20T15:03:22.379Z", "__v": 0 }, { - "_id": "682c706c951f7a0017130024", "message": "Exercise? I thought you said extra fries! 🍟😂", "hearts": 14, "createdAt": "2025-05-20T12:07:08.185Z", "__v": 0 }, { - "_id": "682c6fe1951f7a0017130023", "message": "I’m on a seafood diet. I see food, and I eat it.", "hearts": 4, "createdAt": "2025-05-20T12:04:49.978Z", "__v": 0 }, { - "_id": "682c6f0e951f7a0017130022", "message": "Cute monkeys🐒", "hearts": 2, "createdAt": "2025-05-20T12:01:18.308Z", "__v": 0 }, { - "_id": "682c6e65951f7a0017130021", "message": "The weather is nice!", "hearts": 0, "createdAt": "2025-05-20T11:58:29.662Z", "__v": 0 }, { - "_id": "682bfdb4270ca300105af221", "message": "good vibes and good things", "hearts": 3, "createdAt": "2025-05-20T03:57:40.322Z", "__v": 0 }, { - "_id": "682bab8c12155b00101732ce", "message": "Berlin baby", "hearts": 37, "createdAt": "2025-05-19T22:07:08.999Z", diff --git a/server.js b/server.js index 36dcec3..31e41d5 100644 --- a/server.js +++ b/server.js @@ -4,7 +4,7 @@ import listEndpoints from "express-list-endpoints" import mongoose from "mongoose" import dotenv from "dotenv" -// import thoughtsData from "./data.json" +import thoughtsData from "./data.json" dotenv.config() @@ -21,30 +21,27 @@ const app = express() app.use(cors()) app.use(express.json()) - - const thoughtSchema = new mongoose.Schema({ - _id: String, + message: String, hearts: Number, createdAt: { type: Date, - default: Date.now() + default: Date.now } }) //HĂ€r lĂ€gg const Thought = mongoose.model("Thought", thoughtSchema) -// if (process.env.RESET_DB) { -// const seedDatabase = async () => { -// await Thought.deleteMany({}) -// thoughtsData.forEach(thought => { -// new Thought(thought).save() -// }) -// } -// seedDatabase() -// } - +if (process.env.RESET_DB) { + const seedDatabase = async () => { + await Thought.deleteMany({}) + thoughtsData.forEach(thought => { + new Thought(thought).save() + }) + } + seedDatabase() +} // Start defining your routes here app.get("/", (req, res) => { @@ -55,8 +52,6 @@ app.get("/", (req, res) => { }) }) - - //endpoint for getting all thoughts app.get("/thoughts", async (req, res) => { const { likes, minLikes } = req.query @@ -105,7 +100,6 @@ app.get("/thoughts", async (req, res) => { }) // endpoint for getting one thought - app.get("/thoughts/:id", async (req, res) => { const { id } = req.params @@ -141,9 +135,7 @@ app.get("/thoughts/:id", async (req, res) => { } }) - //endpoint for deleting a thought - app.delete("/thoughts/:id", async (req, res) => { const { id } = req.params @@ -180,17 +172,25 @@ app.delete("/thoughts/:id", async (req, res) => { } }) -// app.delete("/thoughts/:id", (req, res) => { -// const index = thoughts.findIndex(thought => thought._id === req.params.id) +app.post("/thoughts", async (req, res) => { + const { message } = req.body -// if (index == -1) { -// return res.status(404).json({ error: "thought dosnt exist" }) -// } - -// const deletedThought = thoughts.splice(index, 1)[0] -// res.json({ message: "Thought deleted", deletedThought }) -// }) + try { + const newThought = await new Thought({ message }).save() + res.status(201).json({ + success: true, + response: newThought, + message: "Thought was successfully created" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Couldn't create thought" + }) + } +}) // Start the server app.listen(port, () => { From b1b437f081247236ab995a5074878fc03cda895f Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 9 Jun 2025 16:52:07 +0200 Subject: [PATCH 09/28] add default number to hearts --- server.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index 31e41d5..3e7fbe5 100644 --- a/server.js +++ b/server.js @@ -24,7 +24,10 @@ app.use(express.json()) const thoughtSchema = new mongoose.Schema({ message: String, - hearts: Number, + hearts: { + type: Number, + default: 0 + }, createdAt: { type: Date, default: Date.now @@ -192,6 +195,17 @@ app.post("/thoughts", async (req, res) => { } }) +app.patch("/thoughts/:id", async (req, res) => { + const { id } = req.params + const { newhearts } = req.body + + try { + const thought = await Thought.findByIdAndUpdate(id, { hearts: newhearts }) + } catch (error) { + + } +}) + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`) From aa05d014e96a16b47809afe2b7f8b0faae49f6bc Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 9 Jun 2025 21:55:08 +0200 Subject: [PATCH 10/28] Add func to patch --- server.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 3e7fbe5..229f6cd 100644 --- a/server.js +++ b/server.js @@ -180,6 +180,7 @@ app.post("/thoughts", async (req, res) => { try { const newThought = await new Thought({ message }).save() + console.log("Created thought:", newThought) res.status(201).json({ success: true, @@ -200,9 +201,23 @@ app.patch("/thoughts/:id", async (req, res) => { const { newhearts } = req.body try { - const thought = await Thought.findByIdAndUpdate(id, { hearts: newhearts }) + const thought = await Thought.findByIdAndUpdate(id, { hearts: newhearts }, { new: true }) + if (!thought) { + return res.status(404).json({ + success: false, + message: "Thought not found" + }) + } + res.status(200).json({ + success: true, + response: thought + }) } catch (error) { - + res.status(500).json({ + success: false, + message: "Failed to update Likes", + response: error + }) } }) From 4ba6d9a78185ac7fe1d7d0f5aff1397cdb299f28 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Tue, 10 Jun 2025 14:56:07 +0200 Subject: [PATCH 11/28] text --- server.js | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/server.js b/server.js index 229f6cd..cfb9c1f 100644 --- a/server.js +++ b/server.js @@ -36,15 +36,15 @@ const thoughtSchema = new mongoose.Schema({ //HĂ€r lĂ€gg const Thought = mongoose.model("Thought", thoughtSchema) -if (process.env.RESET_DB) { - const seedDatabase = async () => { - await Thought.deleteMany({}) - thoughtsData.forEach(thought => { - new Thought(thought).save() - }) - } - seedDatabase() -} +// if (process.env.RESET_DB) { +// const seedDatabase = async () => { +// await Thought.deleteMany({}) +// thoughtsData.forEach(thought => { +// new Thought(thought).save() +// }) +// } +// seedDatabase() +// } // Start defining your routes here app.get("/", (req, res) => { @@ -198,25 +198,28 @@ app.post("/thoughts", async (req, res) => { app.patch("/thoughts/:id", async (req, res) => { const { id } = req.params - const { newhearts } = req.body try { - const thought = await Thought.findByIdAndUpdate(id, { hearts: newhearts }, { new: true }) + const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) + if (!thought) { return res.status(404).json({ success: false, + response: null, message: "Thought not found" }) } res.status(200).json({ success: true, - response: thought + response: thought, + message: "Updated" }) } catch (error) { res.status(500).json({ success: false, - message: "Failed to update Likes", - response: error + response: error, + message: "Server Error! Failed to update Likes", + }) } }) From 035863297a3d8676be0932092caa5afb89573b4c Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Tue, 10 Jun 2025 15:34:59 +0200 Subject: [PATCH 12/28] test --- server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index cfb9c1f..39d7096 100644 --- a/server.js +++ b/server.js @@ -196,7 +196,7 @@ app.post("/thoughts", async (req, res) => { } }) -app.patch("/thoughts/:id", async (req, res) => { +app.patch("/thoughts/:id/like", async (req, res) => { const { id } = req.params try { @@ -219,7 +219,7 @@ app.patch("/thoughts/:id", async (req, res) => { success: false, response: error, message: "Server Error! Failed to update Likes", - + }) } }) From 92a04bc9ddd56cb4436996e1a6c12c2d5d02f51c Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 11 Jun 2025 10:27:06 +0200 Subject: [PATCH 13/28] functinality for edit --- server.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/server.js b/server.js index 39d7096..5f66436 100644 --- a/server.js +++ b/server.js @@ -138,6 +138,8 @@ app.get("/thoughts/:id", async (req, res) => { } }) + + //endpoint for deleting a thought app.delete("/thoughts/:id", async (req, res) => { const { id } = req.params @@ -224,6 +226,42 @@ app.patch("/thoughts/:id/like", async (req, res) => { } }) +app.patch("/thoughts/:id", async (req, res) => { + const { id } = req.params + const { newMessage } = req.body + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Invalid id" + }) + } + + try { + const thought = await Thought.findByIdAndUpdate({ id }, { message: newMessage }, { new: true, runValidators: true }) + + if (!thought) { + return res.status(404).json({ + success: false, + response: null, + message: "Thought not found" + }) + } + res.status(200).json({ + success: true, + response: thought, + message: "Updated" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server Error! Failed to update Likes", + + }) + } +}) + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`) From 22a4b94c1e6988e36838bcfab68505d5edb15106 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 11 Jun 2025 14:57:10 +0200 Subject: [PATCH 14/28] fix bug in edit --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 5f66436..83ec87b 100644 --- a/server.js +++ b/server.js @@ -225,7 +225,7 @@ app.patch("/thoughts/:id/like", async (req, res) => { }) } }) - +//for updating a thought (editing the message) app.patch("/thoughts/:id", async (req, res) => { const { id } = req.params const { newMessage } = req.body From f3b7814419ce81d30fdcbd3e8cdee56095d9487a Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 11 Jun 2025 15:06:39 +0200 Subject: [PATCH 15/28] Add correct endpoint --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 83ec87b..8cd6dc5 100644 --- a/server.js +++ b/server.js @@ -226,7 +226,7 @@ app.patch("/thoughts/:id/like", async (req, res) => { } }) //for updating a thought (editing the message) -app.patch("/thoughts/:id", async (req, res) => { +app.patch("/thoughts/:id/edit", async (req, res) => { const { id } = req.params const { newMessage } = req.body if (!mongoose.Types.ObjectId.isValid(id)) { From 89ebfd3a9eec958513e64d22e893d39a96a8a8f6 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 11 Jun 2025 16:35:42 +0200 Subject: [PATCH 16/28] correcting error --- server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 8cd6dc5..9fa21bc 100644 --- a/server.js +++ b/server.js @@ -238,7 +238,7 @@ app.patch("/thoughts/:id/edit", async (req, res) => { } try { - const thought = await Thought.findByIdAndUpdate({ id }, { message: newMessage }, { new: true, runValidators: true }) + const thought = await Thought.findByIdAndUpdate( id, { message: newMessage }, { new: true, runValidators: true }) if (!thought) { return res.status(404).json({ @@ -256,7 +256,7 @@ app.patch("/thoughts/:id/edit", async (req, res) => { res.status(500).json({ success: false, response: error, - message: "Server Error! Failed to update Likes", + message: "Server Error! Failed to update Message", }) } From dcfdfa8f53e31c62ae910adcbb3e36a5cf1c5e18 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 11 Jun 2025 17:38:35 +0200 Subject: [PATCH 17/28] trying to text bug --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 9fa21bc..bf6cffa 100644 --- a/server.js +++ b/server.js @@ -228,7 +228,7 @@ app.patch("/thoughts/:id/like", async (req, res) => { //for updating a thought (editing the message) app.patch("/thoughts/:id/edit", async (req, res) => { const { id } = req.params - const { newMessage } = req.body + const { message: newMessage } = req.body if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).json({ success: false, From b1fa723e867a4e849312ff5f56beec0e9bd46a6c Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Thu, 12 Jun 2025 13:33:36 +0200 Subject: [PATCH 18/28] add authentication for user --- package.json | 1 + server.js | 103 +++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 101 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 9c9d350..2fa56a9 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "@babel/core": "^7.17.9", "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", + "bcrypt-nodejs": "^0.0.3", "cors": "^2.8.5", "dotenv": "^16.5.0", "express": "^4.17.3", diff --git a/server.js b/server.js index bf6cffa..6f60bcf 100644 --- a/server.js +++ b/server.js @@ -3,9 +3,12 @@ import express from "express" import listEndpoints from "express-list-endpoints" import mongoose from "mongoose" import dotenv from "dotenv" - +import crypto from "crypto" +import bcrypt from "bcrypt-nodejs" +// Import the data from the JSON file import thoughtsData from "./data.json" + dotenv.config() const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/thoughts" @@ -21,6 +24,50 @@ const app = express() app.use(cors()) app.use(express.json()) + +// Create a schema for the users +const userSchema = new mongoose.Schema({ + name: { + type: String, + required: true, + unique: true + }, + email: { + type: String, + required: true, + unique: true + }, + password: { + type: String, + required: true + }, // Passwords should be hashed in a real application + accessToken: { + type: String, + default: crypto.randomBytes(128).toString("hex") + } // Generate a random access token + +}) +const User = mongoose.model("User", userSchema) + +const authenticateUser = async (req, res, next) => { + const user = await User.findOne({ accessToken: req.headers.authorization }) + if (user) { + req.user = user + next() + }else { + res.status(401).json({ + success: false, + loggedOut: true, + message: "Unauthorized! Please provide a valid access token." + }) + } +} + + + + + +// Create a schema for the thoughts const thoughtSchema = new mongoose.Schema({ message: String, @@ -33,7 +80,7 @@ const thoughtSchema = new mongoose.Schema({ default: Date.now } }) -//HĂ€r lĂ€gg + const Thought = mongoose.model("Thought", thoughtSchema) // if (process.env.RESET_DB) { @@ -46,6 +93,56 @@ const Thought = mongoose.model("Thought", thoughtSchema) // seedDatabase() // } +//middleware that checkes access token when user tries to access the secret endpoint +app.get("/secret", authenticateUser) +//Super secret endpoint +app.get("/secret", (req, res) => { + res.json({ + secret: "This is a super secret message! đŸ€«" + }) +}) +//Login endpoint +app.post("/sessions", async (req, res) => { + const user = await User.findOne({ email: req.body.email }) + if (user && bcrypt.compareSync(req.body.password, user.password)) { + res.json({ + userId: user._id, + accessToken: user.accessToken + }) + //Maybe some error handeling here + }else { + re.json({ notFound: true, message: "User not found or password is incorrect" }) + } +}) +//Create a new user (registration endpoint) +app.post("/users", async (req, res) => { + try { + const { name, email, password } = req.body + const salt = bcrypt.genSaltSync() + const user = new User({ + name, + email, + password: bcrypt.hashSync(password, salt) // Hash the password before saving + }) + user.save() + //If uer is OK + res.status(201).json({ + success: true, + message: "User created successfully", + id: user._id, + accessToken: user.accessToken + + }) + + } catch (error) { + res.status(400).json({ + success: false, + response: error, + message: "Failed to create user. Please check your input." + }) + } +}) + // Start defining your routes here app.get("/", (req, res) => { const endpoints = listEndpoints(app) @@ -238,7 +335,7 @@ app.patch("/thoughts/:id/edit", async (req, res) => { } try { - const thought = await Thought.findByIdAndUpdate( id, { message: newMessage }, { new: true, runValidators: true }) + const thought = await Thought.findByIdAndUpdate(id, { message: newMessage }, { new: true, runValidators: true }) if (!thought) { return res.status(404).json({ From 41db27485383bcb3bc832d85be757012fa4033cf Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Thu, 12 Jun 2025 18:56:34 +0200 Subject: [PATCH 19/28] break out and structure the code --- middleware/authMiddleware.js | 38 +++++ models/Thought.js | 16 ++ models/User.js | 28 ++++ routes/thoughtsRoutes.js | 224 +++++++++++++++++++++++++ routes/userRoutes.js | 51 ++++++ server.js | 315 +---------------------------------- 6 files changed, 366 insertions(+), 306 deletions(-) create mode 100644 middleware/authMiddleware.js create mode 100644 models/Thought.js create mode 100644 models/User.js create mode 100644 routes/thoughtsRoutes.js create mode 100644 routes/userRoutes.js diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js new file mode 100644 index 0000000..823c5d0 --- /dev/null +++ b/middleware/authMiddleware.js @@ -0,0 +1,38 @@ +import { User } from '../models/User.js' + +export const authenticateUser = async (req, res, next) => { + const user = await User.findOne({ accessToken: req.headers.authorization }) + if (user) { + req.user = user + next() + } else { + res.status(401).json({ + success: false, + loggedOut: true, + message: "Unauthorized! Please provide a valid access token." + }) + } +} + + + +// export const authenticateUser = async (req, res, next) => { +// try { +// const user = await User.findOne({ +// accessToken: req.header("Authorization"), +// }); +// if (user) { +// req.user = user; +// next(); +// } else { +// res.status(401).json({ +// message: "Authentication missing or invalid.", +// loggedOut: true, +// }); +// } +// } catch (err) { +// res +// .status(500) +// .json({ message: "Internal server error", error: err.message }); +// } +// }; \ No newline at end of file diff --git a/models/Thought.js b/models/Thought.js new file mode 100644 index 0000000..2cee8c8 --- /dev/null +++ b/models/Thought.js @@ -0,0 +1,16 @@ +import mongoose from "mongoose" + +const thoughtSchema = new mongoose.Schema({ + + message: String, + hearts: { + type: Number, + default: 0 + }, + createdAt: { + type: Date, + default: Date.now + } +}) + +export const Thought = mongoose.model("Thought", thoughtSchema) \ No newline at end of file diff --git a/models/User.js b/models/User.js new file mode 100644 index 0000000..b4cb844 --- /dev/null +++ b/models/User.js @@ -0,0 +1,28 @@ +import mongoose from "mongoose" +import crypto from "crypto" + + +// Create a schema for the users +const userSchema = new mongoose.Schema({ + name: { + type: String, + required: true, + unique: true + }, + email: { + type: String, + required: true, + unique: true + }, + password: { + type: String, + required: true + }, // Passwords should be hashed in a real application + accessToken: { + type: String, + default: crypto.randomBytes(128).toString("hex") + } // Generate a random access token + +}) + +export const User = mongoose.model("User", userSchema) diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js new file mode 100644 index 0000000..7a78cc1 --- /dev/null +++ b/routes/thoughtsRoutes.js @@ -0,0 +1,224 @@ +import express from 'express' +import { Thought } from '../models/Thought.js' +import { authenticateUser } from '../middleware/authMiddleware.js' + +const router = express.Router() +// Get all thoughts + + +//endpoint actually "/thoughts" +router.get("/", async (req, res) => { + const { likes, minLikes } = req.query + + const query = {} + + //Make sure there is error handelning when parameter is not a number + + if (likes !== undefined) { + const numLikes = +likes + if (isNaN(numLikes)) { + return res.status(400).json({ error: "Query parameter 'likes' must be a number." }) + } + query.hearts = numLikes + } + + if (minLikes !== undefined) { + const numMinLikes = +minLikes + if (isNaN(numMinLikes)) { + return res.status(400).json({ error: "Query parameter 'likes' must be a number." }) + } + query.hearts = { $gte: numMinLikes } + } + + try { + const filteredThoughts = await Thought.find(query) + + if (filteredThoughts.length === 0) { + return res.status(404).json({ + success: false, + response: [], + message: "No thougth found for that query. Please try another one" + }) + } + res.status(200).json({ + success: true, + response: filteredThoughts + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server error! Failed to fetch thoughts." + }) + } +}) + +// endpoint for getting one thought actually "/thoughts/:id" +router.get("/:id", async (req, res) => { + const { id } = req.params + + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Invalid id" + }) + } + + try { + const thought = await Thought.findById(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: [], + message: "No thougth found" + }) + } + + res.status(200).json({ + success: true, + response: thought + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server error! Failed to fetch thoughts." + }) + } +}) + + + +// endpoint for creating a thought actually "/thoughts" +router.post("/", async (req, res) => { + const { message } = req.body + + try { + const newThought = await new Thought({ message }).save() + console.log("Created thought:", newThought) + + res.status(201).json({ + success: true, + response: newThought, + message: "Thought was successfully created" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Couldn't create thought" + }) + } +}) + + + +//delete a thought endpoint actually "/thoughts/:id" +router.delete("/:id", async (req, res) => { + const { id } = req.params + + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Could not delete! Invalid id" + }) + } + + try { + const thought = await Thought.findByIdAndDelete(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: [], + message: "No thougth found" + }) + } + + res.status(200).json({ + success: true, + response: thought, + message: "Was successfully deleted" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server error! Failed to fetch thoughts." + }) + } +}) + + +// endpoint for liking a thought actually "/thoughts/:id/like" +router.patch("/:id/like", async (req, res) => { + const { id } = req.params + + try { + const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) + + if (!thought) { + return res.status(404).json({ + success: false, + response: null, + message: "Thought not found" + }) + } + res.status(200).json({ + success: true, + response: thought, + message: "Updated" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server Error! Failed to update Likes", + + }) + } +}) + + + +//for updating a thought message (actuallt "/thoughts/:id/edit") +router.patch("/:id/edit", async (req, res) => { + const { id } = req.params + const { message: newMessage } = req.body + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Invalid id" + }) + } + + try { + const thought = await Thought.findByIdAndUpdate(id, { message: newMessage }, { new: true, runValidators: true }) + + if (!thought) { + return res.status(404).json({ + success: false, + response: null, + message: "Thought not found" + }) + } + res.status(200).json({ + success: true, + response: thought, + message: "Updated" + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Server Error! Failed to update Message", + + }) + } +}) + +export default router \ No newline at end of file diff --git a/routes/userRoutes.js b/routes/userRoutes.js new file mode 100644 index 0000000..5c98c20 --- /dev/null +++ b/routes/userRoutes.js @@ -0,0 +1,51 @@ + +import express from 'express' +import bcrypt from 'bcrypt-nodejs' // Use bcryptjs for compatibility? +import { User } from '../models/User.js' + + +const router = express.Router() + +//Login endpoint actually "/users/login" +router.post("/login", async (req, res) => { + const user = await User.findOne({ email: req.body.email }) + if (user && bcrypt.compareSync(req.body.password, user.password)) { + res.json({ + userId: user._id, + accessToken: user.accessToken + }) + //Maybe some error handeling here + } else { + re.json({ notFound: true, message: "User not found or password is incorrect" }) + } +}) +//Create a new user (registration endpoint actually "/users/signup") +router.post("/signup", async (req, res) => { + try { + const { name, email, password } = req.body + const salt = bcrypt.genSaltSync() + const user = new User({ + name, + email, + password: bcrypt.hashSync(password, salt) // Hash the password before saving + }) + user.save() + //If uer is OK + res.status(201).json({ + success: true, + message: "User created successfully", + id: user._id, + accessToken: user.accessToken + + }) + + } catch (error) { + res.status(400).json({ + success: false, + response: error, + message: "Failed to create user. Please check your input." + }) + } +}) + +export default router \ No newline at end of file diff --git a/server.js b/server.js index 6f60bcf..ca42ffa 100644 --- a/server.js +++ b/server.js @@ -2,11 +2,15 @@ import cors from "cors" import express from "express" import listEndpoints from "express-list-endpoints" import mongoose from "mongoose" + +import userRoutes from "./routes/userRoutes.js" +import thoughtRoutes from "./routes/thoughtsRoutes.js" +import { authenticateUser } from "./middleware/authMiddleware.js" + import dotenv from "dotenv" -import crypto from "crypto" -import bcrypt from "bcrypt-nodejs" + // Import the data from the JSON file -import thoughtsData from "./data.json" +// import thoughtsData from "./data.json" dotenv.config() @@ -25,64 +29,6 @@ app.use(cors()) app.use(express.json()) -// Create a schema for the users -const userSchema = new mongoose.Schema({ - name: { - type: String, - required: true, - unique: true - }, - email: { - type: String, - required: true, - unique: true - }, - password: { - type: String, - required: true - }, // Passwords should be hashed in a real application - accessToken: { - type: String, - default: crypto.randomBytes(128).toString("hex") - } // Generate a random access token - -}) -const User = mongoose.model("User", userSchema) - -const authenticateUser = async (req, res, next) => { - const user = await User.findOne({ accessToken: req.headers.authorization }) - if (user) { - req.user = user - next() - }else { - res.status(401).json({ - success: false, - loggedOut: true, - message: "Unauthorized! Please provide a valid access token." - }) - } -} - - - - - -// Create a schema for the thoughts -const thoughtSchema = new mongoose.Schema({ - - message: String, - hearts: { - type: Number, - default: 0 - }, - createdAt: { - type: Date, - default: Date.now - } -}) - -const Thought = mongoose.model("Thought", thoughtSchema) - // if (process.env.RESET_DB) { // const seedDatabase = async () => { // await Thought.deleteMany({}) @@ -101,47 +47,7 @@ app.get("/secret", (req, res) => { secret: "This is a super secret message! đŸ€«" }) }) -//Login endpoint -app.post("/sessions", async (req, res) => { - const user = await User.findOne({ email: req.body.email }) - if (user && bcrypt.compareSync(req.body.password, user.password)) { - res.json({ - userId: user._id, - accessToken: user.accessToken - }) - //Maybe some error handeling here - }else { - re.json({ notFound: true, message: "User not found or password is incorrect" }) - } -}) -//Create a new user (registration endpoint) -app.post("/users", async (req, res) => { - try { - const { name, email, password } = req.body - const salt = bcrypt.genSaltSync() - const user = new User({ - name, - email, - password: bcrypt.hashSync(password, salt) // Hash the password before saving - }) - user.save() - //If uer is OK - res.status(201).json({ - success: true, - message: "User created successfully", - id: user._id, - accessToken: user.accessToken - }) - - } catch (error) { - res.status(400).json({ - success: false, - response: error, - message: "Failed to create user. Please check your input." - }) - } -}) // Start defining your routes here app.get("/", (req, res) => { @@ -152,212 +58,9 @@ app.get("/", (req, res) => { }) }) -//endpoint for getting all thoughts -app.get("/thoughts", async (req, res) => { - const { likes, minLikes } = req.query - - const query = {} - - //Make sure there is error handelning when parameter is not a number - - if (likes !== undefined) { - const numLikes = +likes - if (isNaN(numLikes)) { - return res.status(400).json({ error: "Query parameter 'likes' must be a number." }) - } - query.hearts = numLikes - } - - if (minLikes !== undefined) { - const numMinLikes = +minLikes - if (isNaN(numMinLikes)) { - return res.status(400).json({ error: "Query parameter 'likes' must be a number." }) - } - query.hearts = { $gte: numMinLikes } - } - - try { - const filteredThoughts = await Thought.find(query) - - if (filteredThoughts.length === 0) { - return res.status(404).json({ - success: false, - response: [], - message: "No thougth found for that query. Please try another one" - }) - } - res.status(200).json({ - success: true, - response: filteredThoughts - }) - } catch (error) { - res.status(500).json({ - success: false, - response: error, - message: "Server error! Failed to fetch thoughts." - }) - } -}) - -// endpoint for getting one thought -app.get("/thoughts/:id", async (req, res) => { - const { id } = req.params - if (!mongoose.Types.ObjectId.isValid(id)) { - return res.status(400).json({ - success: false, - response: [], - message: "Invalid id" - }) - } - - try { - const thought = await Thought.findById(id) - - if (!thought) { - return res.status(404).json({ - success: false, - response: [], - message: "No thougth found" - }) - } - - res.status(200).json({ - success: true, - response: thought - }) - } catch (error) { - res.status(500).json({ - success: false, - response: error, - message: "Server error! Failed to fetch thoughts." - }) - } -}) - - - -//endpoint for deleting a thought -app.delete("/thoughts/:id", async (req, res) => { - const { id } = req.params - - if (!mongoose.Types.ObjectId.isValid(id)) { - return res.status(400).json({ - success: false, - response: [], - message: "Could not delete! Invalid id" - }) - } - - try { - const thought = await Thought.findByIdAndDelete(id) - - if (!thought) { - return res.status(404).json({ - success: false, - response: [], - message: "No thougth found" - }) - } - - res.status(200).json({ - success: true, - response: thought, - message: "Was successfully deleted" - }) - } catch (error) { - res.status(500).json({ - success: false, - response: error, - message: "Server error! Failed to fetch thoughts." - }) - } -}) - -app.post("/thoughts", async (req, res) => { - const { message } = req.body - - try { - const newThought = await new Thought({ message }).save() - console.log("Created thought:", newThought) - - res.status(201).json({ - success: true, - response: newThought, - message: "Thought was successfully created" - }) - } catch (error) { - res.status(500).json({ - success: false, - response: error, - message: "Couldn't create thought" - }) - } -}) - -app.patch("/thoughts/:id/like", async (req, res) => { - const { id } = req.params - - try { - const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) - - if (!thought) { - return res.status(404).json({ - success: false, - response: null, - message: "Thought not found" - }) - } - res.status(200).json({ - success: true, - response: thought, - message: "Updated" - }) - } catch (error) { - res.status(500).json({ - success: false, - response: error, - message: "Server Error! Failed to update Likes", - - }) - } -}) -//for updating a thought (editing the message) -app.patch("/thoughts/:id/edit", async (req, res) => { - const { id } = req.params - const { message: newMessage } = req.body - if (!mongoose.Types.ObjectId.isValid(id)) { - return res.status(400).json({ - success: false, - response: [], - message: "Invalid id" - }) - } - - try { - const thought = await Thought.findByIdAndUpdate(id, { message: newMessage }, { new: true, runValidators: true }) - - if (!thought) { - return res.status(404).json({ - success: false, - response: null, - message: "Thought not found" - }) - } - res.status(200).json({ - success: true, - response: thought, - message: "Updated" - }) - } catch (error) { - res.status(500).json({ - success: false, - response: error, - message: "Server Error! Failed to update Message", - - }) - } -}) +app.use("/users", userRoutes) +app.use("/thoughts", thoughtRoutes) // Start the server app.listen(port, () => { From dfa757103b165d35c41259f2fe36ed4996c0b14f Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Fri, 13 Jun 2025 08:56:49 +0200 Subject: [PATCH 20/28] modify login. Delete name as required --- models/User.js | 2 +- routes/userRoutes.js | 30 ++++++++++++++++-------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/models/User.js b/models/User.js index b4cb844..bc1c205 100644 --- a/models/User.js +++ b/models/User.js @@ -7,7 +7,7 @@ const userSchema = new mongoose.Schema({ name: { type: String, required: true, - unique: true + }, email: { type: String, diff --git a/routes/userRoutes.js b/routes/userRoutes.js index 5c98c20..a655e28 100644 --- a/routes/userRoutes.js +++ b/routes/userRoutes.js @@ -6,19 +6,6 @@ import { User } from '../models/User.js' const router = express.Router() -//Login endpoint actually "/users/login" -router.post("/login", async (req, res) => { - const user = await User.findOne({ email: req.body.email }) - if (user && bcrypt.compareSync(req.body.password, user.password)) { - res.json({ - userId: user._id, - accessToken: user.accessToken - }) - //Maybe some error handeling here - } else { - re.json({ notFound: true, message: "User not found or password is incorrect" }) - } -}) //Create a new user (registration endpoint actually "/users/signup") router.post("/signup", async (req, res) => { try { @@ -30,7 +17,7 @@ router.post("/signup", async (req, res) => { password: bcrypt.hashSync(password, salt) // Hash the password before saving }) user.save() - //If uer is OK + res.status(201).json({ success: true, message: "User created successfully", @@ -48,4 +35,19 @@ router.post("/signup", async (req, res) => { } }) +//Login endpoint actually "/users/login" +router.post("/login", async (req, res) => { + const user = await User.findOne({ email: req.body.email }) + if (user && bcrypt.compareSync(req.body.password, user.password)) { + res.json({ + userId: user._id, + accessToken: user.accessToken + }) + //Maybe some error handeling here + } else { + re.json({ notFound: true, message: "User not found or password is incorrect" }) + } +}) + + export default router \ No newline at end of file From 438de94283bf252d9e19d1bc2d1ce9049756f512 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Sun, 15 Jun 2025 21:37:30 +0200 Subject: [PATCH 21/28] connect specific message to specific user + find and fix bug --- middleware/authMiddleware.js | 2 ++ models/Thought.js | 5 +++++ package.json | 1 + routes/thoughtsRoutes.js | 15 ++++++++++----- routes/userRoutes.js | 27 +++++++++++++++++++-------- server.js | 9 --------- 6 files changed, 37 insertions(+), 22 deletions(-) diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js index 823c5d0..6084305 100644 --- a/middleware/authMiddleware.js +++ b/middleware/authMiddleware.js @@ -1,6 +1,8 @@ import { User } from '../models/User.js' export const authenticateUser = async (req, res, next) => { + + const user = await User.findOne({ accessToken: req.headers.authorization }) if (user) { req.user = user diff --git a/models/Thought.js b/models/Thought.js index 2cee8c8..16457d0 100644 --- a/models/Thought.js +++ b/models/Thought.js @@ -10,6 +10,11 @@ const thoughtSchema = new mongoose.Schema({ createdAt: { type: Date, default: Date.now + }, + user: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true } }) diff --git a/package.json b/package.json index 2fa56a9..eba631c 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", "bcrypt-nodejs": "^0.0.3", + "bcryptjs": "^3.0.2", "cors": "^2.8.5", "dotenv": "^16.5.0", "express": "^4.17.3", diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index 7a78cc1..62e86ef 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -1,4 +1,5 @@ import express from 'express' +import mongoose from 'mongoose' import { Thought } from '../models/Thought.js' import { authenticateUser } from '../middleware/authMiddleware.js' @@ -92,11 +93,14 @@ router.get("/:id", async (req, res) => { // endpoint for creating a thought actually "/thoughts" -router.post("/", async (req, res) => { +router.post("/", authenticateUser, async (req, res) => { const { message } = req.body - + console.log("req.user:", req.user) try { - const newThought = await new Thought({ message }).save() + const newThought = await new Thought({ + message, + user: req.user._id + }).save() console.log("Created thought:", newThought) res.status(201).json({ @@ -105,6 +109,7 @@ router.post("/", async (req, res) => { message: "Thought was successfully created" }) } catch (error) { + console.log("POST error", error) res.status(500).json({ success: false, response: error, @@ -116,7 +121,7 @@ router.post("/", async (req, res) => { //delete a thought endpoint actually "/thoughts/:id" -router.delete("/:id", async (req, res) => { +router.delete("/:id", authenticateUser, async (req, res) => { const { id } = req.params if (!mongoose.Types.ObjectId.isValid(id)) { @@ -185,7 +190,7 @@ router.patch("/:id/like", async (req, res) => { //for updating a thought message (actuallt "/thoughts/:id/edit") -router.patch("/:id/edit", async (req, res) => { +router.patch("/:id/edit", authenticateUser, async (req, res) => { const { id } = req.params const { message: newMessage } = req.body if (!mongoose.Types.ObjectId.isValid(id)) { diff --git a/routes/userRoutes.js b/routes/userRoutes.js index a655e28..37c5576 100644 --- a/routes/userRoutes.js +++ b/routes/userRoutes.js @@ -1,6 +1,6 @@ import express from 'express' -import bcrypt from 'bcrypt-nodejs' // Use bcryptjs for compatibility? +import bcrypt from 'bcryptjs'// Use bcryptjs for compatibility? import { User } from '../models/User.js' @@ -9,14 +9,17 @@ const router = express.Router() //Create a new user (registration endpoint actually "/users/signup") router.post("/signup", async (req, res) => { try { - const { name, email, password } = req.body + const { name, password } = req.body + //make sure email is lowercase + const email = req.body.email.trim().toLowerCase() const salt = bcrypt.genSaltSync() const user = new User({ name, email, password: bcrypt.hashSync(password, salt) // Hash the password before saving }) - user.save() + //await to not send response before database finished saving + await user.save() res.status(201).json({ success: true, @@ -37,15 +40,23 @@ router.post("/signup", async (req, res) => { //Login endpoint actually "/users/login" router.post("/login", async (req, res) => { - const user = await User.findOne({ email: req.body.email }) + //make sure email is lowercase + const email = req.body.email.trim().toLowerCase() + const user = await User.findOne({ email }) + if (user && bcrypt.compareSync(req.body.password, user.password)) { - res.json({ + res.status(200).json({ + success: true, + accessToken: user.accessToken, userId: user._id, - accessToken: user.accessToken + message: "Login successful", }) - //Maybe some error handeling here } else { - re.json({ notFound: true, message: "User not found or password is incorrect" }) + //Login failed + res.status(401).json({ + success: false, + message: "User not found or password is incorrect", + }); } }) diff --git a/server.js b/server.js index ca42ffa..dc77b77 100644 --- a/server.js +++ b/server.js @@ -39,15 +39,6 @@ app.use(express.json()) // seedDatabase() // } -//middleware that checkes access token when user tries to access the secret endpoint -app.get("/secret", authenticateUser) -//Super secret endpoint -app.get("/secret", (req, res) => { - res.json({ - secret: "This is a super secret message! đŸ€«" - }) -}) - // Start defining your routes here app.get("/", (req, res) => { From 6e11864100b4ab2418fa728113a83afd95d1a343 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 16 Jun 2025 21:42:24 +0200 Subject: [PATCH 22/28] up the security --- routes/thoughtsRoutes.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index 62e86ef..f6f39f7 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -133,7 +133,11 @@ router.delete("/:id", authenticateUser, async (req, res) => { } try { - const thought = await Thought.findByIdAndDelete(id) + //Check if this message really belong to the user thats logged in + const thought = await Thought.findByIdAndDelete({ + _id: id, + user: req.user._id + }) if (!thought) { return res.status(404).json({ @@ -163,7 +167,10 @@ router.patch("/:id/like", async (req, res) => { const { id } = req.params try { - const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) + const thought = await Thought.findByIdAndUpdate({ + _id: id, + user: req.user._id + }, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) if (!thought) { return res.status(404).json({ From 68aafd1ddf01ef4c0830532b8d1c031ce49fef97 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 16 Jun 2025 22:11:37 +0200 Subject: [PATCH 23/28] Fix bug --- routes/thoughtsRoutes.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index f6f39f7..46fae5a 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -167,10 +167,7 @@ router.patch("/:id/like", async (req, res) => { const { id } = req.params try { - const thought = await Thought.findByIdAndUpdate({ - _id: id, - user: req.user._id - }, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) + const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) if (!thought) { return res.status(404).json({ @@ -209,7 +206,10 @@ router.patch("/:id/edit", authenticateUser, async (req, res) => { } try { - const thought = await Thought.findByIdAndUpdate(id, { message: newMessage }, { new: true, runValidators: true }) + const thought = await Thought.findByIdAndUpdate({ + _id: id, + user: req.user._id + }, { message: newMessage }, { new: true, runValidators: true }) if (!thought) { return res.status(404).json({ From fd99adfef834427ee906001c87a77f1ea4915a07 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Tue, 17 Jun 2025 17:52:30 +0200 Subject: [PATCH 24/28] make get function to get liked messages --- models/Thought.js | 6 +++++- routes/thoughtsRoutes.js | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/models/Thought.js b/models/Thought.js index 16457d0..439b79c 100644 --- a/models/Thought.js +++ b/models/Thought.js @@ -15,7 +15,11 @@ const thoughtSchema = new mongoose.Schema({ type: mongoose.Schema.Types.ObjectId, ref: "User", required: true - } + }, + likedBy: [{ + type: mongoose.Schema.Types.ObjectId, + ref: "User" + }] }) export const Thought = mongoose.model("Thought", thoughtSchema) \ No newline at end of file diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index 46fae5a..be107b5 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -54,6 +54,24 @@ router.get("/", async (req, res) => { } }) +// endpoint for getting liked thoughts actually "/thoughts/liked" +router.get("/liked", authenticateUser, async (req, res) => { + const userId = req.user._id + try { + const likedThoughts = await Thought.find({ likedBy: req.user._id }) + res.status(200).json({ + success: true, + response: likedThoughts + }) + } catch (error) { + res.status(500).json({ + success: false, + response: error, + message: "Could not get liked thoughts" + }) + } +}) + // endpoint for getting one thought actually "/thoughts/:id" router.get("/:id", async (req, res) => { const { id } = req.params @@ -92,6 +110,8 @@ router.get("/:id", async (req, res) => { + + // endpoint for creating a thought actually "/thoughts" router.post("/", authenticateUser, async (req, res) => { const { message } = req.body @@ -165,6 +185,7 @@ router.delete("/:id", authenticateUser, async (req, res) => { // endpoint for liking a thought actually "/thoughts/:id/like" router.patch("/:id/like", async (req, res) => { const { id } = req.params + try { const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) @@ -176,6 +197,9 @@ router.patch("/:id/like", async (req, res) => { message: "Thought not found" }) } + + // Add the user to the likedBy array if not already present + res.status(200).json({ success: true, response: thought, From 00c0807da90dba2ef6a3a7703840bad6515d1562 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Wed, 18 Jun 2025 23:42:58 +0200 Subject: [PATCH 25/28] fix the count of likes --- middleware/authMiddleware.js | 74 +++++++++++++++++++----------------- models/Like.js | 24 ++++++++++++ models/Thought.js | 12 +++--- routes/thoughtsRoutes.js | 62 +++++++++++++++++++++++++++--- 4 files changed, 127 insertions(+), 45 deletions(-) create mode 100644 models/Like.js diff --git a/middleware/authMiddleware.js b/middleware/authMiddleware.js index 6084305..5f2c352 100644 --- a/middleware/authMiddleware.js +++ b/middleware/authMiddleware.js @@ -1,40 +1,46 @@ import { User } from '../models/User.js' + export const authenticateUser = async (req, res, next) => { - - - const user = await User.findOne({ accessToken: req.headers.authorization }) - if (user) { - req.user = user - next() - } else { - res.status(401).json({ - success: false, - loggedOut: true, - message: "Unauthorized! Please provide a valid access token." - }) + try { + const accessToken = req.header("Authorization") + const user = await User.findOne({ accessToken: accessToken }) + if (user) { + req.user = user + next() + } else { + res.status(401).json({ + message: "Authentication missing or invalid.", + loggedOut: true + }) + } + } catch (error) { + res.status(500).json({ + message: "Internal server error", + error: error.message + }); } } - - -// export const authenticateUser = async (req, res, next) => { -// try { -// const user = await User.findOne({ -// accessToken: req.header("Authorization"), -// }); -// if (user) { -// req.user = user; -// next(); -// } else { -// res.status(401).json({ -// message: "Authentication missing or invalid.", -// loggedOut: true, -// }); -// } -// } catch (err) { -// res -// .status(500) -// .json({ message: "Internal server error", error: err.message }); -// } -// }; \ No newline at end of file +export const authenticateUserLike = async (req, res, next) => { + try { + const accessToken = req.header("Authorization") + if (accessToken) { + const user = await User.findOne({ accessToken: accessToken }) + if (user) { + req.user = user + } else { + return res.status(401).json({ + message: "Authentication missing or invalid.", + loggedOut: true + }) + } + } + next() + } catch (error) { + res.status(500).json({ + message: "Internal server error", + error: error.message + }) + } +} \ No newline at end of file diff --git a/models/Like.js b/models/Like.js new file mode 100644 index 0000000..3d35ca1 --- /dev/null +++ b/models/Like.js @@ -0,0 +1,24 @@ +import mongoose from "mongoose" + +const likeSchema = new mongoose.Schema({ + user: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true + }, + thought: { + type: mongoose.Schema.Types.ObjectId, + ref: "Thought", + required: true + }, + createdAt: { + type: Date, + default: Date.now + } +}) + +// will make sure a user can only like a thought one time +// +likeSchema.index({ user: 1, thought: 1 }, { unique: true }) + +export const Like = mongoose.model("Like", likeSchema) \ No newline at end of file diff --git a/models/Thought.js b/models/Thought.js index 439b79c..ef50fa2 100644 --- a/models/Thought.js +++ b/models/Thought.js @@ -2,7 +2,12 @@ import mongoose from "mongoose" const thoughtSchema = new mongoose.Schema({ - message: String, + message: { + type: String, + required: true, + minLength: 5, + maxLength: 140 + }, hearts: { type: Number, default: 0 @@ -16,10 +21,7 @@ const thoughtSchema = new mongoose.Schema({ ref: "User", required: true }, - likedBy: [{ - type: mongoose.Schema.Types.ObjectId, - ref: "User" - }] + }) export const Thought = mongoose.model("Thought", thoughtSchema) \ No newline at end of file diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index be107b5..06c35e6 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -1,7 +1,9 @@ import express from 'express' import mongoose from 'mongoose' import { Thought } from '../models/Thought.js' -import { authenticateUser } from '../middleware/authMiddleware.js' +import { authenticateUser, authenticateUserLike } from '../middleware/authMiddleware.js' +import { User } from '../models/User.js' +import { Like } from '../models/Like.js' const router = express.Router() // Get all thoughts @@ -56,9 +58,24 @@ router.get("/", async (req, res) => { // endpoint for getting liked thoughts actually "/thoughts/liked" router.get("/liked", authenticateUser, async (req, res) => { + const { minLikes } = req.query const userId = req.user._id + try { - const likedThoughts = await Thought.find({ likedBy: req.user._id }) + let likedThoughts = await Thought.find({ likedBy: userId }) + + if (minLikes !== undefined) { + const min = parseInt(minLikes) + if (isNaN(min)) { + return res.status(400).json({ + success: false, + message: "Query parameter 'minLikes' must be a number." + }) + } + + likedThoughts = likedThoughts.filter(thought => thought.hearts >= min) + } + res.status(200).json({ success: true, response: likedThoughts @@ -183,12 +200,45 @@ router.delete("/:id", authenticateUser, async (req, res) => { // endpoint for liking a thought actually "/thoughts/:id/like" -router.patch("/:id/like", async (req, res) => { +router.patch("/:id/like", authenticateUserLike, async (req, res) => { const { id } = req.params - try { - const thought = await Thought.findByIdAndUpdate(id, { $inc: { hearts: 1 } }, { new: true, runValidators: true }) + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: [], + message: "Invalid id" + }) + } + + // Check if the user has already liked this thought + if (req.user) { + const existingLike = await Like.findOne({ + user: req.user._id, + thought: id + }) + + if (existingLike) { + return res.status(400).json({ + success: false, + response: null, + message: "You have already liked this thought" + }) + } else { + // Create a new like if the user hasn't liked this thought yet + await new Like({ + user: req.user._id, + thought: id + }).save() + } + } + + const thought = await Thought.findByIdAndUpdate( + id, + { $inc: { hearts: 1 } }, + { new: true, runValidators: true } + ) if (!thought) { return res.status(404).json({ @@ -198,7 +248,7 @@ router.patch("/:id/like", async (req, res) => { }) } - // Add the user to the likedBy array if not already present + res.status(200).json({ success: true, From cab7ae00608cc9f464ea060dfc40e40d130657be Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 23 Jun 2025 15:06:53 +0200 Subject: [PATCH 26/28] fix show liked messages bug --- routes/thoughtsRoutes.js | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index 06c35e6..207dec3 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -62,29 +62,35 @@ router.get("/liked", authenticateUser, async (req, res) => { const userId = req.user._id try { - let likedThoughts = await Thought.find({ likedBy: userId }) + // 1. Find all likes by this user + const likes = await Like.find({ user: userId }).select('thought') + // 2. Extract thought IDs + const thoughtIds = likes.map(like => like.thought) + // 3. Build query to find those thoughts + const query = { _id: { $in: thoughtIds } } if (minLikes !== undefined) { const min = parseInt(minLikes) if (isNaN(min)) { return res.status(400).json({ success: false, - message: "Query parameter 'minLikes' must be a number." + message: "Query parameter 'minLikes' must be a number.", }) } - - likedThoughts = likedThoughts.filter(thought => thought.hearts >= min) + query.hearts = { $gte: min } } + // 4. Find and return the liked thoughts + const likedThoughts = await Thought.find(query) res.status(200).json({ success: true, - response: likedThoughts + response: likedThoughts, }) } catch (error) { res.status(500).json({ success: false, response: error, - message: "Could not get liked thoughts" + message: "Could not get liked thoughts.", }) } }) From 68bcbd2701423e440c9a3739ca7aa58a9dd147a5 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 23 Jun 2025 15:20:32 +0200 Subject: [PATCH 27/28] delete console.logs --- routes/thoughtsRoutes.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index 207dec3..f3c1250 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -2,7 +2,6 @@ import express from 'express' import mongoose from 'mongoose' import { Thought } from '../models/Thought.js' import { authenticateUser, authenticateUserLike } from '../middleware/authMiddleware.js' -import { User } from '../models/User.js' import { Like } from '../models/Like.js' const router = express.Router() @@ -138,13 +137,13 @@ router.get("/:id", async (req, res) => { // endpoint for creating a thought actually "/thoughts" router.post("/", authenticateUser, async (req, res) => { const { message } = req.body - console.log("req.user:", req.user) + try { const newThought = await new Thought({ message, user: req.user._id }).save() - console.log("Created thought:", newThought) + res.status(201).json({ success: true, @@ -152,7 +151,6 @@ router.post("/", authenticateUser, async (req, res) => { message: "Thought was successfully created" }) } catch (error) { - console.log("POST error", error) res.status(500).json({ success: false, response: error, From 8d8e1cee0886d7b576f31ecc7468996924b0a915 Mon Sep 17 00:00:00 2001 From: MalLunBar Date: Mon, 23 Jun 2025 17:09:04 +0200 Subject: [PATCH 28/28] clean --- routes/thoughtsRoutes.js | 4 ++-- server.js | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/routes/thoughtsRoutes.js b/routes/thoughtsRoutes.js index f3c1250..a3d7b15 100644 --- a/routes/thoughtsRoutes.js +++ b/routes/thoughtsRoutes.js @@ -137,13 +137,13 @@ router.get("/:id", async (req, res) => { // endpoint for creating a thought actually "/thoughts" router.post("/", authenticateUser, async (req, res) => { const { message } = req.body - + try { const newThought = await new Thought({ message, user: req.user._id }).save() - + res.status(201).json({ success: true, diff --git a/server.js b/server.js index dc77b77..f554f2d 100644 --- a/server.js +++ b/server.js @@ -5,7 +5,6 @@ import mongoose from "mongoose" import userRoutes from "./routes/userRoutes.js" import thoughtRoutes from "./routes/thoughtsRoutes.js" -import { authenticateUser } from "./middleware/authMiddleware.js" import dotenv from "dotenv"