From 0051aa5c4e6b658c1e0039dd007a59a296f67b10 Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Wed, 18 Dec 2024 17:42:41 +0100 Subject: [PATCH 1/8] fork and copy hp api --- package.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 1c371b45..fd2b206e 100644 --- a/package.json +++ b/package.json @@ -12,9 +12,10 @@ "@babel/core": "^7.17.9", "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", + "body-parser": "^1.20.3", "cors": "^2.8.5", - "express": "^4.17.3", - "mongoose": "^8.0.0", + "express": "^4.21.2", + "mongoose": "^8.9.1", "nodemon": "^3.0.1" } -} \ No newline at end of file +} From daa18335ddbaa4bc5f9347ad60d2ff564b444c6a Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Fri, 20 Dec 2024 17:36:41 +0100 Subject: [PATCH 2/8] mongo_url --- package.json | 4 +++ server.js | 100 ++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 99 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index fd2b206e..165b09e1 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "project-happy-thoughts-api", "version": "1.0.0", "description": "Starter project to get up and running with express quickly", + "type": "module", "scripts": { "start": "babel-node server.js", "dev": "nodemon server.js --exec babel-node" @@ -14,7 +15,10 @@ "@babel/preset-env": "^7.16.11", "body-parser": "^1.20.3", "cors": "^2.8.5", + "dotenv": "^16.4.7", "express": "^4.21.2", + "express-list-endpoints": "^7.1.1", + "mongodb": "^6.12.0", "mongoose": "^8.9.1", "nodemon": "^3.0.1" } diff --git a/server.js b/server.js index dfe86fb8..a37d9e77 100644 --- a/server.js +++ b/server.js @@ -1,26 +1,116 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; +import expressListEndpoints from "express-list-endpoints"; +import dotenv from "dotenv"; + + +dotenv.config(); + const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; -mongoose.connect(mongoUrl); +/* mongoose.connect(mongoUrl); */ +mongoose.connect(mongoUrl) + .then(() => console.log('Connected to MongoDB')) + .catch(err => { + console.error('Failed to connect to MongoDB:', err); + process.exit(1); + }); mongoose.Promise = Promise; // 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 -const port = process.env.PORT || 8080; +const port = process.env.PORT; const app = express(); // Add middlewares to enable cors and json body parsing -app.use(cors()); +app.use(cors({ + origin: "https://merry-buttercream-88f52d.netlify.app/", + methods: ["GET", "POST"], + allowedHeaders: ["*"], +})); + app.use(express.json()); -// Start defining your routes here + +// happyThought schema/model +const HappyThought = mongoose.model("HappyThought", new mongoose.Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140 + }, + hearts: { + type: Number, + default: 0 + }, + createdAt: { + type: Date, + default: () => new Date() + } +})) + +// all routes/endpoints app.get("/", (req, res) => { - res.send("Hello Technigo!"); + + const endpoints = expressListEndpoints(app); + res.json({ + message: "Endpoints for happy thought message:", + description: { + "/happythoughts": "all thoughts" + }, + endpoints: endpoints + }); +}); + +// Get all happy thoughts +app.get("/happythoughts", async (req, res) => { + try { + const happyThoughts = await HappyThought.find().sort({createdAt: "desc"}).limit(20).exec(); + res.json(happyThoughts) + } catch (error) { + console.error('Error retrieving thoughts', error); + res.status(500).send('Server error'); + } }); +// Post a happy thought +app.post("/happythoughts", async (req, res) => { + try{ + const { message } = req.body; + const newHappyThought = await new HappyThought ({ message }).save(); + + res.status(201).json(newHappyThought); + } catch(error) { + res.status(400).json({message: "Could not save thought", errors: error.err.errors}) + } +}); + +// Post a happy thought +app.post("/happythoughts/:thoughtId/like", async (req, res) => { + try { + const { id } = req.params; + + // Uppdatera likes för den tanke som matchar ID + const updatedThought = await Thought.findByIdAndUpdate( + id, + { $inc: { hearts: 1 } }, // Incrementera hearts med 1 + { new: true } // Returnera det uppdaterade dokumentet + ); + + if (!updatedThought) { + return res.status(404).json({ success: false, message: 'Thought not found' }); + } + + res.status(200).json({ success: true, response: updatedThought }); + } catch (error) { + res.status(400).json({ success: false, error: error.message }); + } +}); + + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); From e689ecc28a93e65d1f9e5ac773a3e4c3a2044192 Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Sun, 22 Dec 2024 21:48:30 +0100 Subject: [PATCH 3/8] update in code post --- server.js | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/server.js b/server.js index a37d9e77..340f5f9f 100644 --- a/server.js +++ b/server.js @@ -25,12 +25,7 @@ const port = process.env.PORT; const app = express(); // Add middlewares to enable cors and json body parsing -app.use(cors({ - origin: "https://merry-buttercream-88f52d.netlify.app/", - methods: ["GET", "POST"], - allowedHeaders: ["*"], -})); - +app.use(cors()); app.use(express.json()); @@ -69,10 +64,10 @@ app.get("/", (req, res) => { app.get("/happythoughts", async (req, res) => { try { const happyThoughts = await HappyThought.find().sort({createdAt: "desc"}).limit(20).exec(); - res.json(happyThoughts) + res.status(200).json(happyThoughts); } catch (error) { console.error('Error retrieving thoughts', error); - res.status(500).send('Server error'); + res.status(400).send('Server error'); } }); @@ -80,7 +75,7 @@ app.get("/happythoughts", async (req, res) => { app.post("/happythoughts", async (req, res) => { try{ const { message } = req.body; - const newHappyThought = await new HappyThought ({ message }).save(); + const newHappyThought = await new HappyThought({ message }).save(); res.status(201).json(newHappyThought); } catch(error) { @@ -91,13 +86,12 @@ app.post("/happythoughts", async (req, res) => { // Post a happy thought app.post("/happythoughts/:thoughtId/like", async (req, res) => { try { - const { id } = req.params; + const { thoughtId } = req.params; - // Uppdatera likes för den tanke som matchar ID - const updatedThought = await Thought.findByIdAndUpdate( - id, - { $inc: { hearts: 1 } }, // Incrementera hearts med 1 - { new: true } // Returnera det uppdaterade dokumentet + const updatedThought = await HappyThought.findByIdAndUpdate( + thoughtId, + { $inc: { hearts: 1 } }, + { new: true } ); if (!updatedThought) { From c01ae7a9d8d720554cebd49858912a63715b07aa Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Tue, 31 Dec 2024 13:53:36 +0100 Subject: [PATCH 4/8] update: small updates and fallback server --- instructions.md | 13 +++++++++++++ server.js | 13 ++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/instructions.md b/instructions.md index fa87eb1c..e981c396 100644 --- a/instructions.md +++ b/instructions.md @@ -31,6 +31,19 @@ We mentioned the `Thought` model and its properties a bit earlier. Each of these - Defaults to the current time - Should not be assignable when creating a new thought +//seed db +if (process.env.RESET_DB) { + const seedDatabase = async () => { + await HappyThought.deleteMany({}) + + booksData.forEach((book) => { + new HappyThought(book).save() + }) + } + + seedDatabase() +} + ### Using your API Once you've created your API, you should deploy it, and update your frontend project to use your own API instead of the old Technigo one. The idea is that if you build this API correctly, **the only thing you should need to change in the frontend code is the URL to the API,** to change it from the Technigo one to the one you deploy. diff --git a/server.js b/server.js index 340f5f9f..fd7514e2 100644 --- a/server.js +++ b/server.js @@ -21,7 +21,7 @@ mongoose.Promise = Promise; // 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 -const port = process.env.PORT; +const port = process.env.PORT || 8080; const app = express(); // Add middlewares to enable cors and json body parsing @@ -30,7 +30,7 @@ app.use(express.json()); // happyThought schema/model -const HappyThought = mongoose.model("HappyThought", new mongoose.Schema({ +const HappyThoughtSchema = new mongoose.Schema({ message: { type: String, required: true, @@ -45,7 +45,9 @@ const HappyThought = mongoose.model("HappyThought", new mongoose.Schema({ type: Date, default: () => new Date() } -})) +}); + +const HappyThought = mongoose.model("HappyThought", HappyThoughtSchema); // all routes/endpoints app.get("/", (req, res) => { @@ -53,9 +55,6 @@ app.get("/", (req, res) => { const endpoints = expressListEndpoints(app); res.json({ message: "Endpoints for happy thought message:", - description: { - "/happythoughts": "all thoughts" - }, endpoints: endpoints }); }); @@ -83,7 +82,7 @@ app.post("/happythoughts", async (req, res) => { } }); -// Post a happy thought +// Like a happy thought app.post("/happythoughts/:thoughtId/like", async (req, res) => { try { const { thoughtId } = req.params; From 6d13fa30c7b7bcaa15968c5eb436e98f1f7d0732 Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Sun, 5 Jan 2025 15:51:43 +0100 Subject: [PATCH 5/8] Update: id --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index fd7514e2..919396fc 100644 --- a/server.js +++ b/server.js @@ -85,7 +85,7 @@ app.post("/happythoughts", async (req, res) => { // Like a happy thought app.post("/happythoughts/:thoughtId/like", async (req, res) => { try { - const { thoughtId } = req.params; + const { thoughtId } = req.params._id; const updatedThought = await HappyThought.findByIdAndUpdate( thoughtId, From 71f4430a4d26eaca3277b820702618f0d1c988f1 Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Tue, 7 Jan 2025 15:20:40 +0100 Subject: [PATCH 6/8] clean up in code --- server.js | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/server.js b/server.js index 919396fc..4fde1581 100644 --- a/server.js +++ b/server.js @@ -65,8 +65,8 @@ app.get("/happythoughts", async (req, res) => { const happyThoughts = await HappyThought.find().sort({createdAt: "desc"}).limit(20).exec(); res.status(200).json(happyThoughts); } catch (error) { - console.error('Error retrieving thoughts', error); - res.status(400).send('Server error'); + console.error("Error retrieving thoughts", error); + res.status(400).send("Server error"); } }); @@ -78,15 +78,18 @@ app.post("/happythoughts", async (req, res) => { res.status(201).json(newHappyThought); } catch(error) { - res.status(400).json({message: "Could not save thought", errors: error.err.errors}) + res.status(400).json({ + message: "Could not save thought", + errors: error.err.errors + }); } }); // Like a happy thought -app.post("/happythoughts/:thoughtId/like", async (req, res) => { - try { - const { thoughtId } = req.params._id; +app.patch("/happythoughts/:thoughtId/like", async (req, res) => { + const { thoughtId } = req.params; + try { const updatedThought = await HappyThought.findByIdAndUpdate( thoughtId, { $inc: { hearts: 1 } }, @@ -94,12 +97,21 @@ app.post("/happythoughts/:thoughtId/like", async (req, res) => { ); if (!updatedThought) { - return res.status(404).json({ success: false, message: 'Thought not found' }); + return res.status(404).json({ + success: false, + message: "Thought not found" + }); } - res.status(200).json({ success: true, response: updatedThought }); + res.status(200).json({ + success: true, + response: updatedThought + }); } catch (error) { - res.status(400).json({ success: false, error: error.message }); + res.status(400).json({ + success: false, + error: error.message + }); } }); From b8ee3ce4d40d4d6e46b6b64b9558b6dfca95ec54 Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Wed, 8 Jan 2025 21:52:58 +0100 Subject: [PATCH 7/8] update: thoughtid > id --- server.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/server.js b/server.js index 4fde1581..ccaf2559 100644 --- a/server.js +++ b/server.js @@ -86,12 +86,12 @@ app.post("/happythoughts", async (req, res) => { }); // Like a happy thought -app.patch("/happythoughts/:thoughtId/like", async (req, res) => { - const { thoughtId } = req.params; +app.patch("/happythoughts/:id/like", async (req, res) => { + const { id } = req.params; try { const updatedThought = await HappyThought.findByIdAndUpdate( - thoughtId, + id, { $inc: { hearts: 1 } }, { new: true } ); From 3c8c70fad195795c78a28a3e8e11009987214eea Mon Sep 17 00:00:00 2001 From: Erika Olsson Date: Wed, 8 Jan 2025 22:10:37 +0100 Subject: [PATCH 8/8] patch>post --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index ccaf2559..f581ba8b 100644 --- a/server.js +++ b/server.js @@ -86,7 +86,7 @@ app.post("/happythoughts", async (req, res) => { }); // Like a happy thought -app.patch("/happythoughts/:id/like", async (req, res) => { +app.post("/happythoughts/:id/like", async (req, res) => { const { id } = req.params; try {