From 9d660453b21e3b6cbddda5bd63930397891f0a0a Mon Sep 17 00:00:00 2001 From: Jonash189 Date: Thu, 19 Dec 2024 19:45:27 +0100 Subject: [PATCH 1/4] Built RESTful API endpoints to handle thoughts, likes, and timestamps, using MongoDB for data storage. Deployed the backend to Render with MongoDB Atlas for remote database access, while maintaining local development support. --- package.json | 8 +++- server.js | 127 ++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 121 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 1c371b45..028ca600 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", + "main": "server.js", "scripts": { "start": "babel-node server.js", "dev": "nodemon server.js --exec babel-node" @@ -11,10 +12,13 @@ "dependencies": { "@babel/core": "^7.17.9", "@babel/node": "^7.16.8", - "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", "express": "^4.17.3", "mongoose": "^8.0.0", "nodemon": "^3.0.1" - } + }, + "devDependencies": { + "@babel/preset-env": "^7.26.0" + }, + "type": "module" } \ No newline at end of file diff --git a/server.js b/server.js index dfe86fb8..a4643fa0 100644 --- a/server.js +++ b/server.js @@ -1,27 +1,130 @@ -import cors from "cors"; import express from "express"; +import cors from "cors"; import mongoose from "mongoose"; +import dotenv from "dotenv"; +dotenv.config(); + -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; -mongoose.connect(mongoUrl); -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 || 8081; const app = express(); -// Add middlewares to enable cors and json body parsing +// Middleware app.use(cors()); app.use(express.json()); -// Start defining your routes here +// Mongoose connection +const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/happyThoughts"; + +mongoose.connect(mongoUrl, { + useNewUrlParser: true, + useUnifiedTopology: true, +}); +mongoose.Promise = Promise; + +mongoose.connection.on("connected", () => { + console.log(`Connected to MongoDB at ${mongoUrl}`); +}); + +mongoose.connection.on("error", (error) => { + console.error("Error connecting to MongoDB:", error); +}); + + +const { Schema, model } = mongoose; + +// Thought schema +const thoughtSchema = new Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140, + }, + hearts: { + type: Number, + default: 0, + }, + createdAt: { + type: Date, + default: Date.now, + }, +}); + +const Thought = model("Thought", thoughtSchema); + +// Root endpoint app.get("/", (req, res) => { - res.send("Hello Technigo!"); + res.send("Welcome to the Happy Thoughts API!"); +}); + +// Get thoughts (max 20, sorted by createdAt descending) +app.get("/thoughts", async (req, res) => { + try { + const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20); + res.json(thoughts); + } catch (error) { + res.status(500).json({ + success: false, + message: "Could not fetch thoughts.", + error: error.message, + }); + } +}); + +// Post a new thought +app.post("/thoughts", async (req, res) => { + const { message } = req.body; + + try { + const thought = await new Thought({ message }).save(); + res.status(201).json({ + success: true, + message: "Thought created successfully!", + data: thought, + }); + } catch (error) { + res.status(400).json({ + success: false, + message: "Could not create thought. Please check the input.", + error: error.message, + }); + } +}); + +// Add a like to a thought +app.post("/thoughts/:thoughtId/like", async (req, res) => { + const { thoughtId } = req.params; + + try { + const updatedThought = await Thought.findByIdAndUpdate( + thoughtId, + { $inc: { hearts: 1 } }, + { new: true } + ); + + if (!updatedThought) { + return res.status(404).json({ + success: false, + message: "Thought not found.", + }); + } + + res.status(200).json({ + success: true, + message: "Like added successfully!", + data: updatedThought, + }); + } catch (error) { + res.status(400).json({ + success: false, + message: "Could not add like.", + error: error.message, + }); + } }); -// Start the server +// Start server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); }); From 6e5e8dc9e5bf50b5e13daed6367f3a1e3c584e0c Mon Sep 17 00:00:00 2001 From: Jonash189 Date: Thu, 19 Dec 2024 19:52:12 +0100 Subject: [PATCH 2/4] installing dotenv --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 028ca600..04ffc163 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "@babel/core": "^7.17.9", "@babel/node": "^7.16.8", "cors": "^2.8.5", + "dotenv": "^16.4.7", "express": "^4.17.3", "mongoose": "^8.0.0", "nodemon": "^3.0.1" @@ -21,4 +22,4 @@ "@babel/preset-env": "^7.26.0" }, "type": "module" -} \ No newline at end of file +} From bb5fe3c1b37a284c3c829d17c34d38db54aeee45 Mon Sep 17 00:00:00 2001 From: Jonash189 Date: Thu, 19 Dec 2024 20:48:15 +0100 Subject: [PATCH 3/4] Adding cors --- server.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server.js b/server.js index a4643fa0..d4cb12a2 100644 --- a/server.js +++ b/server.js @@ -2,6 +2,9 @@ import express from "express"; import cors from "cors"; import mongoose from "mongoose"; import dotenv from "dotenv"; +import cors from "cors"; + +app.use(cors()); dotenv.config(); From 0ab7e7592b41b41242ff055950bc21b403667d6d Mon Sep 17 00:00:00 2001 From: Jonash189 Date: Thu, 19 Dec 2024 21:22:55 +0100 Subject: [PATCH 4/4] updating the code --- server.js | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/server.js b/server.js index d4cb12a2..a1158d2b 100644 --- a/server.js +++ b/server.js @@ -2,13 +2,9 @@ import express from "express"; import cors from "cors"; import mongoose from "mongoose"; import dotenv from "dotenv"; -import cors from "cors"; -app.use(cors()); dotenv.config(); - - const port = process.env.PORT || 8081; const app = express(); @@ -18,7 +14,6 @@ app.use(express.json()); // Mongoose connection const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/happyThoughts"; - mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true, @@ -33,11 +28,8 @@ mongoose.connection.on("error", (error) => { console.error("Error connecting to MongoDB:", error); }); - -const { Schema, model } = mongoose; - -// Thought schema -const thoughtSchema = new Schema({ +// Mongoose schema and model +const thoughtSchema = new mongoose.Schema({ message: { type: String, required: true, @@ -54,7 +46,7 @@ const thoughtSchema = new Schema({ }, }); -const Thought = model("Thought", thoughtSchema); +const Thought = mongoose.model("Thought", thoughtSchema); // Root endpoint app.get("/", (req, res) => { @@ -81,11 +73,7 @@ app.post("/thoughts", async (req, res) => { try { const thought = await new Thought({ message }).save(); - res.status(201).json({ - success: true, - message: "Thought created successfully!", - data: thought, - }); + res.status(201).json(thought); } catch (error) { res.status(400).json({ success: false, @@ -103,7 +91,7 @@ app.post("/thoughts/:thoughtId/like", async (req, res) => { const updatedThought = await Thought.findByIdAndUpdate( thoughtId, { $inc: { hearts: 1 } }, - { new: true } + { new: true } // Return the updated document ); if (!updatedThought) { @@ -113,11 +101,7 @@ app.post("/thoughts/:thoughtId/like", async (req, res) => { }); } - res.status(200).json({ - success: true, - message: "Like added successfully!", - data: updatedThought, - }); + res.status(200).json(updatedThought); } catch (error) { res.status(400).json({ success: false,