From 951f73ee769b0eb95b524a23ebb82598f5f0798c Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Wed, 15 May 2024 20:29:55 +0200 Subject: [PATCH 1/8] Install needed dependencies and add middleware to check database status --- package.json | 4 +++- server.js | 21 +++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 1c371b45..c6a59c4b 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,10 @@ "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", + "dotenv": "^16.4.5", "express": "^4.17.3", + "express-list-endpoints": "^7.1.0", "mongoose": "^8.0.0", "nodemon": "^3.0.1" } -} \ No newline at end of file +} diff --git a/server.js b/server.js index dfe86fb8..4e18a638 100644 --- a/server.js +++ b/server.js @@ -1,8 +1,15 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; +import dotenv from "dotenv"; +import expressListEndpoints from "express-list-endpoints"; -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; +// Configure dotenv +dotenv.config(); + +// Set up mongoURL and localhost +const mongoUrl = + process.env.MONGO_URL || "mongodb://localhost/happy-thoughts-api"; mongoose.connect(mongoUrl); mongoose.Promise = Promise; @@ -12,9 +19,19 @@ mongoose.Promise = Promise; const port = process.env.PORT || 8080; const app = express(); -// Add middlewares to enable cors and json body parsing +// ---- MIDDLEWARES ---- + +// Middlewares to enable cors and json body parsing app.use(cors()); app.use(express.json()); +// Middleware to check database status +app.use((req, res, next) => { + if (mongoose.connection.readyState === 1) { + next(); + } else { + res.status(503).json({ error: "Service unavailable" }); + } +}); // Start defining your routes here app.get("/", (req, res) => { From 175ff88e9ab12523e32e377bd0487314cfc22047 Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Wed, 15 May 2024 20:35:02 +0200 Subject: [PATCH 2/8] Add endpoint for API documentation --- server.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 4e18a638..1489c089 100644 --- a/server.js +++ b/server.js @@ -33,9 +33,19 @@ app.use((req, res, next) => { } }); -// Start defining your routes here +// ---- ROUTES ---- + +// GET API documentation app.get("/", (req, res) => { - res.send("Hello Technigo!"); + try { + const endpoints = expressListEndpoints(app); + res.json(endpoints); + } catch (error) { + console.error("Error", error); + res + .status(500) + .send("This page is unavailable at the moment. Please try again later."); + } }); // Start the server From 186e9fe30691590331a527f17984c829dcf7cd39 Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Wed, 15 May 2024 21:01:02 +0200 Subject: [PATCH 3/8] Create Thought model and define schema --- models/ThoughtSchema.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 models/ThoughtSchema.js diff --git a/models/ThoughtSchema.js b/models/ThoughtSchema.js new file mode 100644 index 00000000..69c2e31a --- /dev/null +++ b/models/ThoughtSchema.js @@ -0,0 +1,24 @@ +import mongoose from "mongoose"; + +const { Schema } = mongoose; + +export const ThoughtSchema = new Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140, + }, + hearts: { + type: Number, + default: 0, + }, + createdAt: { + type: Date, + default: Date.now, + }, +}); + +// Mongoose model +const Thought = mongoose.model("Thought", ThoughtSchema); +export default Thought; From 7069b7d8e21476dddb28add070b00acac78ecd28 Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Wed, 15 May 2024 21:47:25 +0200 Subject: [PATCH 4/8] Create endpoints to get all thoughts and to post thoughts --- server.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/server.js b/server.js index 1489c089..c78e7bbf 100644 --- a/server.js +++ b/server.js @@ -3,6 +3,7 @@ import express from "express"; import mongoose from "mongoose"; import dotenv from "dotenv"; import expressListEndpoints from "express-list-endpoints"; +import Thought from "./models/ThoughtSchema"; // Configure dotenv dotenv.config(); @@ -48,6 +49,38 @@ app.get("/", (req, res) => { } }); +// GET thoughts +app.get("/thoughts", async (req, res) => { + const allThoughts = await Thought.find(); + res.json(allThoughts); +}); + +// POST thought +app.post("/thoughts", async (req, res) => { + const { message } = req.body; + + try { + // Success case - create thought + const thought = await new Thought({ + message, + }).save(); + + // Set success status + res.status(201).json({ + success: true, + response: thought, + message: "Thought created successfully", + }); + } catch (error) { + // Failed case - return error message + res.status(400).json({ + sucess: false, + response: error, + message: "Unable to create thought", + }); + } +}); + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); From 92f3339e73752a4019abc3a3f0e1225b3661fbfa Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Wed, 15 May 2024 22:20:37 +0200 Subject: [PATCH 5/8] Create endpoint for posting likes --- server.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/server.js b/server.js index c78e7bbf..0bfe2361 100644 --- a/server.js +++ b/server.js @@ -81,6 +81,28 @@ app.post("/thoughts", async (req, res) => { } }); +// POST like +app.post("/thoughts/:thoughtId/like", async (req, res) => { + const { thoughtId } = req.params; + + try { + const thought = await Thought.findById(thoughtId).exec(); + + if (thought) { + // Add one like + thought.hearts++; + // Save thought object + thought.save(); + res.json(thought); + } else { + res.status(404).send("Could not find thought"); + } + } catch (error) { + console.error("Error", error); + res.status(404).send("Could not find thought"); + } +}); + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); From c1f0627f95f70daf63c8e0650ee0eb1bfe155d9e Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Wed, 15 May 2024 23:03:31 +0200 Subject: [PATCH 6/8] Update mongo url with collection name --- server.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 0bfe2361..8bd126ae 100644 --- a/server.js +++ b/server.js @@ -5,7 +5,7 @@ import dotenv from "dotenv"; import expressListEndpoints from "express-list-endpoints"; import Thought from "./models/ThoughtSchema"; -// Configure dotenv +// Load environment variables dotenv.config(); // Set up mongoURL and localhost @@ -51,7 +51,10 @@ app.get("/", (req, res) => { // GET thoughts app.get("/thoughts", async (req, res) => { - const allThoughts = await Thought.find(); + const allThoughts = await Thought.find() + .sort({ createdAt: "desc" }) + .limit(20) + .exec(); res.json(allThoughts); }); From 0ab221ba82bff921516d498681002f19ad28aee4 Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Sat, 18 May 2024 22:05:07 +0200 Subject: [PATCH 7/8] Return only thought object in post request --- server.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/server.js b/server.js index 8bd126ae..1d9d944d 100644 --- a/server.js +++ b/server.js @@ -69,11 +69,7 @@ app.post("/thoughts", async (req, res) => { }).save(); // Set success status - res.status(201).json({ - success: true, - response: thought, - message: "Thought created successfully", - }); + res.status(201).json(thought); } catch (error) { // Failed case - return error message res.status(400).json({ From 5e0ff254bdff4d88b3121b8350711590e5cad0c8 Mon Sep 17 00:00:00 2001 From: Frida Svensson Date: Sat, 18 May 2024 23:29:34 +0200 Subject: [PATCH 8/8] Update README --- README.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 6a75d8e1..ff857cfc 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,17 @@ # Project Happy Thoughts API -Replace this readme with your own information about your project. - -Start by briefly describing the assignment in a sentence or two. Keep it short and to the point. +API to support the Happy Thoughts Project. Serve get requests and handle post request by querying a mongo database. ## The problem -Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next? +I set up a connection to a database, MongoDB, and added endpoints needed to support the Happy Thoughts frontend using Express. Changed url in frontend to point to new server. + +Further on I would like to try out and add more features like pagination and allowing the user to either be anonymous or to enter their name when they post their happy thought. ## View it live -Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about. +Backend: +https://project-happy-thoughts-api-rn3z.onrender.com + +Frontend: +https://happy-thoughts-fms.netlify.app/