From d1fc583975717d2701b6a566e0e7912d678cf3e3 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 15:11:45 +0100 Subject: [PATCH 01/26] - defined mongoose schema and model and first endpoints with get and post options; - connected to mongodb altas as a database --- package.json | 3 ++- server.js | 76 +++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 1c371b45..963f2abc 100644 --- a/package.json +++ b/package.json @@ -13,8 +13,9 @@ "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", + "dotenv": "^16.4.7", "express": "^4.17.3", "mongoose": "^8.0.0", "nodemon": "^3.0.1" } -} \ No newline at end of file +} diff --git a/server.js b/server.js index dfe86fb8..21a47b92 100644 --- a/server.js +++ b/server.js @@ -1,10 +1,48 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; +import dotenv from "dotenv"; -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; -mongoose.connect(mongoUrl); -mongoose.Promise = Promise; +dotenv.config() + +//const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/thoughts"; + +const mongoURI = process.env.MONGODB_URI + +mongoose.connect(mongoURI) +.then(() => { + console.log('MongoDB successfully connected!') + }) + .catch((error) => { + console.error('Error to connect with MongoDB', error) + }) + +//mongoose.Promise = Promise; + +// Setting a Schema and model +const Thought = mongoose.model("Thought", new mongoose.Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 500 + }, + heart: { + type: Boolean, + default: false + }, + likedBy: [{ + type: mongoose.Schema.Types.ObjectId, //stores preferences to user object + ref:"User" + }], + createdAt: { + type: Date, + default: () => new Date() + } +})) + +//check if validation is working +new Thought({message: "hallo"}).save(); // 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,7 +59,37 @@ app.get("/", (req, res) => { res.send("Hello Technigo!"); }); +app.get("/thoughts", async (req, res) => { + try { + // returning 20 thoughts in descending order + const thoughts = await Thought.find().sort({createAt: "desc"}).limit(20).exec(); + res.json(thoughts) + }catch (error) { + console.error('Error retrieving thoughts', error); + res.status(500).send('Server error'); + } + }); + + app.post("/thoughts", async (req, res) => { + try{ + //retrieve the information sent by the client to our API endpoint + const {message, heart} = req.body; + //use the mongoose model to create the DB entry + const newThought = new Thought({ + message, + heart, + }); + await newThought.save(); + + res.status(201).json(newThought); + } catch(error) { + res.status(400).json({message: "Could not save thought", errors: error.err.errors}) + } + }); + app.post("/thoughts/:id/like", async (req, res) => { + }) + // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); -}); +}); \ No newline at end of file From dd7810ca0f012febaeafae862623f615578270c6 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 16:01:01 +0100 Subject: [PATCH 02/26] - fixed mongoose model and added an endpoint to update the hearts --- server.js | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/server.js b/server.js index 21a47b92..fe09423b 100644 --- a/server.js +++ b/server.js @@ -25,11 +25,11 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ type: String, required: true, minlength: 5, - maxlength: 500 + maxlength: 140 }, - heart: { - type: Boolean, - default: false + hearts: { + type: Number, + default: 0 }, likedBy: [{ type: mongoose.Schema.Types.ObjectId, //stores preferences to user object @@ -62,7 +62,7 @@ app.get("/", (req, res) => { app.get("/thoughts", async (req, res) => { try { // returning 20 thoughts in descending order - const thoughts = await Thought.find().sort({createAt: "desc"}).limit(20).exec(); + const thoughts = await Thought.find().sort({createdAt: "desc"}).limit(20).exec(); res.json(thoughts) }catch (error) { console.error('Error retrieving thoughts', error); @@ -72,13 +72,10 @@ app.get("/thoughts", async (req, res) => { app.post("/thoughts", async (req, res) => { try{ - //retrieve the information sent by the client to our API endpoint - const {message, heart} = req.body; + //retrieve the information sent by the client to the API endpoint + const {message} = req.body; //use the mongoose model to create the DB entry - const newThought = new Thought({ - message, - heart, - }); + const newThought = new Thought({message}); await newThought.save(); res.status(201).json(newThought); @@ -86,7 +83,25 @@ app.get("/thoughts", async (req, res) => { res.status(400).json({message: "Could not save thought", errors: error.err.errors}) } }); + + // Like a thought (increase of hearts) app.post("/thoughts/:id/like", async (req, res) => { + try { + const {id} = req.params; + // Find the thought by ID and update the hearts count + const updatedThought = await Thought.findByIdAndUpdate( + id, + {$inc: {hearts:1}}, + {new: true} + ); + if(!updatedThought) { + return res.status(404).json({message: "Thought not found"}); + } + res.status(200).json(updatedThought); + } catch (error){ + console.error("There is an errow by liking the thought", error); + res.status(500).jason({message: "Could not like thought"}) + } }) // Start the server From f18a48ed0d33d6657b0ffef928cf9a3e0c2e6d26 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:01:55 +0100 Subject: [PATCH 03/26] - added corse middleware to accept requests from netlify --- server.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server.js b/server.js index fe09423b..fd96d0b4 100644 --- a/server.js +++ b/server.js @@ -54,6 +54,8 @@ const app = express(); app.use(cors()); app.use(express.json()); +const allowedOrigins = ["https://post-happy-thoughts.netlify.app"] + // Start defining your routes here app.get("/", (req, res) => { res.send("Hello Technigo!"); From 21fe4e2cba2843b2301286c6914db40afa974e83 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:11:19 +0100 Subject: [PATCH 04/26] = I needed to set the origin property in the cors configuration --- server.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/server.js b/server.js index fd96d0b4..6bb57725 100644 --- a/server.js +++ b/server.js @@ -54,8 +54,14 @@ const app = express(); app.use(cors()); app.use(express.json()); +// Define allowed origins const allowedOrigins = ["https://post-happy-thoughts.netlify.app"] +// use CORS middleware with specific origin +app.use(cors({ + origin: allowedOrigins +})); + // Start defining your routes here app.get("/", (req, res) => { res.send("Hello Technigo!"); From 768c32133ce49fc91c0d8be1b4a9d8d1a5caab08 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:17:12 +0100 Subject: [PATCH 05/26] - commented cors out --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 6bb57725..3122195f 100644 --- a/server.js +++ b/server.js @@ -51,7 +51,7 @@ const port = process.env.PORT || 8080; const app = express(); // Add middlewares to enable cors and json body parsing -app.use(cors()); +// app.use(cors()); app.use(express.json()); // Define allowed origins From 5cf5f569bcf053504305c491a220d23fb9f1ce34 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:19:51 +0100 Subject: [PATCH 06/26] -added CORS configuration --- server.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/server.js b/server.js index 3122195f..f5dc0203 100644 --- a/server.js +++ b/server.js @@ -57,6 +57,12 @@ app.use(express.json()); // Define allowed origins const allowedOrigins = ["https://post-happy-thoughts.netlify.app"] +app.use(cors({ + origin: allowedOrigins, // Allow requests only from this origin + methods: ["GET", "POST"], // Allow only GET and POST methods + allowedHeaders: ["Content-Type"], // Allow only Content-Type headers +})); + // use CORS middleware with specific origin app.use(cors({ origin: allowedOrigins From fde9c3ffd875fe0a70862af0f11abb05d568d10a Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:26:44 +0100 Subject: [PATCH 07/26] = trying to fix cors --- server.js | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/server.js b/server.js index f5dc0203..3c7b92cc 100644 --- a/server.js +++ b/server.js @@ -55,18 +55,9 @@ const app = express(); app.use(express.json()); // Define allowed origins -const allowedOrigins = ["https://post-happy-thoughts.netlify.app"] - -app.use(cors({ - origin: allowedOrigins, // Allow requests only from this origin - methods: ["GET", "POST"], // Allow only GET and POST methods - allowedHeaders: ["Content-Type"], // Allow only Content-Type headers -})); - -// use CORS middleware with specific origin app.use(cors({ - origin: allowedOrigins -})); + origin: "https://post-happy-thoughts.netlify.app" +})) // Start defining your routes here app.get("/", (req, res) => { From 709d87c191e53ad5a1bc628282c0d782335de6df Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:49:16 +0100 Subject: [PATCH 08/26] - still trying to fix cors problems --- server.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/server.js b/server.js index 3c7b92cc..1db11771 100644 --- a/server.js +++ b/server.js @@ -40,25 +40,22 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ default: () => new Date() } })) - -//check if validation is working -new Thought({message: "hallo"}).save(); - // 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 app = express(); +app.use(cors({ + origin: "https://post-happy-thoughts.netlify.app", // your frontend URL + methods: ["GET", "POST"], // Specify allowed methods + allowedHeaders: ["Content-Type"] // Specify allowed headers +})); + // Add middlewares to enable cors and json body parsing // app.use(cors()); app.use(express.json()); -// Define allowed origins -app.use(cors({ - origin: "https://post-happy-thoughts.netlify.app" -})) - // Start defining your routes here app.get("/", (req, res) => { res.send("Hello Technigo!"); From f231b0935e0b85ecbcea75cc0780c84963ddabb8 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 17:56:10 +0100 Subject: [PATCH 09/26] = changed mongoose model --- server.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 1db11771..8076b3b0 100644 --- a/server.js +++ b/server.js @@ -35,10 +35,10 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ type: mongoose.Schema.Types.ObjectId, //stores preferences to user object ref:"User" }], - createdAt: { - type: Date, - default: () => new Date() - } + // createdAt: { + // type: Date, + // default: () => new Date() + // } })) // 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: From 8f1725a387076529a9ec1dd9f0e58d01e4ec20d2 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 18:01:24 +0100 Subject: [PATCH 10/26] -cors --- server.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/server.js b/server.js index 8076b3b0..f731939e 100644 --- a/server.js +++ b/server.js @@ -1,4 +1,4 @@ -import cors from "cors"; +// import cors from "cors"; import express from "express"; import mongoose from "mongoose"; import dotenv from "dotenv"; @@ -46,11 +46,11 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ const port = process.env.PORT || 8080; const app = express(); -app.use(cors({ - origin: "https://post-happy-thoughts.netlify.app", // your frontend URL - methods: ["GET", "POST"], // Specify allowed methods - allowedHeaders: ["Content-Type"] // Specify allowed headers -})); +// app.use(cors({ +// origin: "https://post-happy-thoughts.netlify.app", // your frontend URL +// methods: ["GET", "POST"], // Specify allowed methods +// allowedHeaders: ["Content-Type"] // Specify allowed headers +// })); // Add middlewares to enable cors and json body parsing // app.use(cors()); From 01cea839c1281bb3ddd25c24ed8b6c9d97408925 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 18:15:36 +0100 Subject: [PATCH 11/26] =cors --- server.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/server.js b/server.js index f731939e..1db11771 100644 --- a/server.js +++ b/server.js @@ -1,4 +1,4 @@ -// import cors from "cors"; +import cors from "cors"; import express from "express"; import mongoose from "mongoose"; import dotenv from "dotenv"; @@ -35,10 +35,10 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ type: mongoose.Schema.Types.ObjectId, //stores preferences to user object ref:"User" }], - // createdAt: { - // type: Date, - // default: () => new Date() - // } + createdAt: { + type: Date, + default: () => new Date() + } })) // 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: @@ -46,11 +46,11 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ const port = process.env.PORT || 8080; const app = express(); -// app.use(cors({ -// origin: "https://post-happy-thoughts.netlify.app", // your frontend URL -// methods: ["GET", "POST"], // Specify allowed methods -// allowedHeaders: ["Content-Type"] // Specify allowed headers -// })); +app.use(cors({ + origin: "https://post-happy-thoughts.netlify.app", // your frontend URL + methods: ["GET", "POST"], // Specify allowed methods + allowedHeaders: ["Content-Type"] // Specify allowed headers +})); // Add middlewares to enable cors and json body parsing // app.use(cors()); From 76dabbdd482614ec1e826d35b2034f625ff15358 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 18:26:06 +0100 Subject: [PATCH 12/26] - cors --- server.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/server.js b/server.js index 1db11771..c539bdaa 100644 --- a/server.js +++ b/server.js @@ -46,11 +46,15 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ const port = process.env.PORT || 8080; const app = express(); -app.use(cors({ - origin: "https://post-happy-thoughts.netlify.app", // your frontend URL - methods: ["GET", "POST"], // Specify allowed methods - allowedHeaders: ["Content-Type"] // Specify allowed headers -})); +app.use((req, res, next) => { + res.setHeader("Access-Control-Allow-Origin", "https://post-happy-thoughts.netlify.app") +}) + +// app.use(cors({ +// origin: "https://post-happy-thoughts.netlify.app", // your frontend URL +// methods: ["GET", "POST"], // Specify allowed methods +// allowedHeaders: ["Content-Type"] // Specify allowed headers +// })); // Add middlewares to enable cors and json body parsing // app.use(cors()); From b0048547f5007c5f6dbc40e5f59583b5812e884a Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 18:39:25 +0100 Subject: [PATCH 13/26] - cors --- server.js | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/server.js b/server.js index c539bdaa..1db11771 100644 --- a/server.js +++ b/server.js @@ -46,15 +46,11 @@ const Thought = mongoose.model("Thought", new mongoose.Schema({ const port = process.env.PORT || 8080; const app = express(); -app.use((req, res, next) => { - res.setHeader("Access-Control-Allow-Origin", "https://post-happy-thoughts.netlify.app") -}) - -// app.use(cors({ -// origin: "https://post-happy-thoughts.netlify.app", // your frontend URL -// methods: ["GET", "POST"], // Specify allowed methods -// allowedHeaders: ["Content-Type"] // Specify allowed headers -// })); +app.use(cors({ + origin: "https://post-happy-thoughts.netlify.app", // your frontend URL + methods: ["GET", "POST"], // Specify allowed methods + allowedHeaders: ["Content-Type"] // Specify allowed headers +})); // Add middlewares to enable cors and json body parsing // app.use(cors()); From 5b1cd8d2e9280b2608f735359b19533ad87369bb Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 19:50:35 +0100 Subject: [PATCH 14/26] - cors --- server.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index 1db11771..336e7928 100644 --- a/server.js +++ b/server.js @@ -47,9 +47,10 @@ const port = process.env.PORT || 8080; const app = express(); app.use(cors({ - origin: "https://post-happy-thoughts.netlify.app", // your frontend URL + origin: "*", methods: ["GET", "POST"], // Specify allowed methods - allowedHeaders: ["Content-Type"] // Specify allowed headers + allowedHeaders: ["*"], // Specify allowed headers + credetials: true })); // Add middlewares to enable cors and json body parsing From be4b15f8b540594aacf146509f2cc083d31ed960 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 20:22:11 +0100 Subject: [PATCH 15/26] -cors --- server.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 336e7928..7924dd7c 100644 --- a/server.js +++ b/server.js @@ -5,9 +5,9 @@ import dotenv from "dotenv"; dotenv.config() -//const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/thoughts"; +const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/thoughts"; -const mongoURI = process.env.MONGODB_URI +// const mongoURI = process.env.MONGODB_URI mongoose.connect(mongoURI) .then(() => { @@ -47,10 +47,10 @@ const port = process.env.PORT || 8080; const app = express(); app.use(cors({ - origin: "*", + origin: "https://post-happy-thoughts.netlify.app", methods: ["GET", "POST"], // Specify allowed methods allowedHeaders: ["*"], // Specify allowed headers - credetials: true + // credetials: true })); // Add middlewares to enable cors and json body parsing From 329e729e853c79855f6f117d900b262ff81ec120 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 20:32:24 +0100 Subject: [PATCH 16/26] - cleaned code --- server.js | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/server.js b/server.js index 7924dd7c..694ad34d 100644 --- a/server.js +++ b/server.js @@ -17,8 +17,6 @@ mongoose.connect(mongoURI) console.error('Error to connect with MongoDB', error) }) -//mongoose.Promise = Promise; - // Setting a Schema and model const Thought = mongoose.model("Thought", new mongoose.Schema({ message: { @@ -49,12 +47,9 @@ const app = express(); app.use(cors({ origin: "https://post-happy-thoughts.netlify.app", methods: ["GET", "POST"], // Specify allowed methods - allowedHeaders: ["*"], // Specify allowed headers - // credetials: true + allowedHeaders: ["*"], // Specify allowed headers, in this case all })); -// Add middlewares to enable cors and json body parsing -// app.use(cors()); app.use(express.json()); // Start defining your routes here From 9d5502226b119b369778bd63c971d9d61e47fe5e Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 20:37:23 +0100 Subject: [PATCH 17/26] - cors --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 694ad34d..251cd611 100644 --- a/server.js +++ b/server.js @@ -45,7 +45,7 @@ const port = process.env.PORT || 8080; const app = express(); app.use(cors({ - origin: "https://post-happy-thoughts.netlify.app", + origin: "*", methods: ["GET", "POST"], // Specify allowed methods allowedHeaders: ["*"], // Specify allowed headers, in this case all })); From 44b98437e919dcbc297ba4bc5763c5a4c43f1a61 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 20:43:25 +0100 Subject: [PATCH 18/26] -cors --- server.js | 1 + 1 file changed, 1 insertion(+) diff --git a/server.js b/server.js index 251cd611..5bc47b00 100644 --- a/server.js +++ b/server.js @@ -48,6 +48,7 @@ app.use(cors({ origin: "*", methods: ["GET", "POST"], // Specify allowed methods allowedHeaders: ["*"], // Specify allowed headers, in this case all + credentials: true })); app.use(express.json()); From 77aef36e6432ea108d46cc65415efcb8c9a25e15 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 20:49:20 +0100 Subject: [PATCH 19/26] -changed api --- server.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server.js b/server.js index 5bc47b00..6b272182 100644 --- a/server.js +++ b/server.js @@ -5,9 +5,9 @@ import dotenv from "dotenv"; dotenv.config() -const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/thoughts"; +// const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/thoughts"; -// const mongoURI = process.env.MONGODB_URI +const mongoURI = process.env.MONGODB_URI mongoose.connect(mongoURI) .then(() => { @@ -45,10 +45,10 @@ const port = process.env.PORT || 8080; const app = express(); app.use(cors({ - origin: "*", + origin: "https://post-happy-thoughts.netlify.app/", methods: ["GET", "POST"], // Specify allowed methods allowedHeaders: ["*"], // Specify allowed headers, in this case all - credentials: true + // credentials: true })); app.use(express.json()); From 0a9cf7d3be3567aeed92868cb2d9c1ac4594d986 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 20:52:52 +0100 Subject: [PATCH 20/26] - fixed api --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 6b272182..93e96688 100644 --- a/server.js +++ b/server.js @@ -45,7 +45,7 @@ const port = process.env.PORT || 8080; const app = express(); app.use(cors({ - origin: "https://post-happy-thoughts.netlify.app/", + origin: "https://post-happy-thoughts.netlify.app", methods: ["GET", "POST"], // Specify allowed methods allowedHeaders: ["*"], // Specify allowed headers, in this case all // credentials: true From 12bdfa2bcdef62836feca2376f36fef2f0db666b Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Wed, 18 Dec 2024 21:36:17 +0100 Subject: [PATCH 21/26] - added readme file --- README.md | 38 +++++++++++++++++++++++++++++++++----- server.js | 3 --- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6a75d8e1..b3fe23c3 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,41 @@ # Project Happy Thoughts API -Replace this readme with your own information about your project. +This is a backend API for the Happy Thoughts app, built using Express.js, MongoDB (via Mongoose), and CORS. -Start by briefly describing the assignment in a sentence or two. Keep it short and to the point. +The app allows users to post, retrieve, and like "thoughts" (messages), which are stored in a MongoDB database. -## The problem +## Features +Post Thoughts: Users can submit a message (between 5 to 140 characters) to create a new thought. + +Like Thoughts: Users can "like" a thought, which increases the "hearts" count for that particular thought. + +Get Thoughts: Users can retrieve the latest 20 thoughts, sorted in descending order by creation date. + +CORS Support: The API allows cross-origin requests from a specific frontend hosted on Netlify (https://post-happy-thoughts.netlify.app). + +## Technologies Used +Node.js: Backend runtime environment. + +Express.js: Web framework for building the API. + +MongoDB: NoSQL database used to store thoughts and related data. + +Mongoose: MongoDB object modeling tool. + +dotenv: For managing environment variables. + +CORS: Cross-origin resource sharing to allow specific domains to interact with the API. + +## API Endpoints + +GET /thoughts: Retrieves the 20 most recent thoughts. + +POST /thoughts: Submits a new thought with a message. + +POST /thoughts/:id/like: Likes a thought by incrementing the hearts count. -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? ## View it live +project-happy-thoughts-api-production-5d1d.up.railway.app + -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. diff --git a/server.js b/server.js index 93e96688..893eed76 100644 --- a/server.js +++ b/server.js @@ -5,8 +5,6 @@ import dotenv from "dotenv"; dotenv.config() -// const mongoUrl = process.env.MONGO_URL || "mongodb://127.0.0.1:27017/thoughts"; - const mongoURI = process.env.MONGODB_URI mongoose.connect(mongoURI) @@ -48,7 +46,6 @@ app.use(cors({ origin: "https://post-happy-thoughts.netlify.app", methods: ["GET", "POST"], // Specify allowed methods allowedHeaders: ["*"], // Specify allowed headers, in this case all - // credentials: true })); app.use(express.json()); From d45bb49fec4759e2b254e823a78a48fdf9ea3e05 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Thu, 19 Dec 2024 08:03:56 +0100 Subject: [PATCH 22/26] - added list of endpoints --- package.json | 1 + server.js | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 963f2abc..1193322b 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.17.3", + "express-list-endpoints": "^7.1.1", "mongoose": "^8.0.0", "nodemon": "^3.0.1" } diff --git a/server.js b/server.js index 893eed76..645d955f 100644 --- a/server.js +++ b/server.js @@ -2,6 +2,7 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; import dotenv from "dotenv"; +import listEndpoints from "express-list-endpoints"; dotenv.config() @@ -52,7 +53,11 @@ app.use(express.json()); // Start defining your routes here app.get("/", (req, res) => { - res.send("Hello Technigo!"); + const endpoints = listEndpoints(app); + res.json({ + message: "These are the endpoints of the Happy Thoughts API", + endpoints: endpoints + }) }); app.get("/thoughts", async (req, res) => { From 4c901fd6142289d6a91d587c7b45d3772ca72c46 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Thu, 19 Dec 2024 08:36:51 +0100 Subject: [PATCH 23/26] - changed the like function so that it can both add or substract hearts --- server.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/server.js b/server.js index 645d955f..c26462f4 100644 --- a/server.js +++ b/server.js @@ -88,16 +88,27 @@ app.get("/thoughts", async (req, res) => { // Like a thought (increase of hearts) app.post("/thoughts/:id/like", async (req, res) => { try { - const {id} = req.params; - // Find the thought by ID and update the hearts count - const updatedThought = await Thought.findByIdAndUpdate( - id, - {$inc: {hearts:1}}, - {new: true} - ); - if(!updatedThought) { - return res.status(404).json({message: "Thought not found"}); + const {id} = req.params + const thought = await Thought.findById(id) + if(!thought) { + return res.status(404).json({message: "Thought was not found"}) } + if (thought.hearts %2=== 0) { + thought.hearts+=1 + } else { + thought.hearts -=1 + } + const updatedThought = await thought.save() + + // const {id} = req.params; + // const updatedThought = await Thought.findByIdAndUpdate( + // id, + // {$inc: {hearts:1}}, + // {new: true} + // ); + // if(!updatedThought) { + // return res.status(404).json({message: "Thought not found"}); + // } res.status(200).json(updatedThought); } catch (error){ console.error("There is an errow by liking the thought", error); From 79bddff83fbcce6f3833b215e871924c8bf4bd6b Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Thu, 19 Dec 2024 08:43:44 +0100 Subject: [PATCH 24/26] - cleaned code --- server.js | 9 --------- 1 file changed, 9 deletions(-) diff --git a/server.js b/server.js index c26462f4..d9f40cfd 100644 --- a/server.js +++ b/server.js @@ -100,15 +100,6 @@ app.get("/thoughts", async (req, res) => { } const updatedThought = await thought.save() - // const {id} = req.params; - // const updatedThought = await Thought.findByIdAndUpdate( - // id, - // {$inc: {hearts:1}}, - // {new: true} - // ); - // if(!updatedThought) { - // return res.status(404).json({message: "Thought not found"}); - // } res.status(200).json(updatedThought); } catch (error){ console.error("There is an errow by liking the thought", error); From ae9de1b71b54695fecd9af59097bce171dc2b715 Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Tue, 7 Jan 2025 17:24:37 +0100 Subject: [PATCH 25/26] - changed method to update hearts --- server.js | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/server.js b/server.js index d9f40cfd..f8de35ad 100644 --- a/server.js +++ b/server.js @@ -85,7 +85,7 @@ app.get("/thoughts", async (req, res) => { } }); - // Like a thought (increase of hearts) + // Like a thought app.post("/thoughts/:id/like", async (req, res) => { try { const {id} = req.params @@ -93,12 +93,10 @@ app.get("/thoughts", async (req, res) => { if(!thought) { return res.status(404).json({message: "Thought was not found"}) } - if (thought.hearts %2=== 0) { - thought.hearts+=1 - } else { - thought.hearts -=1 - } - const updatedThought = await thought.save() + + // Update hearts count + const newHearts = thought.hearts % 2 ===0 ? thought.hearts +1 : thought.hearts -1; + await Thought.findByIdAndUpdate(id, {hearts: newHearts}, {new: true}); res.status(200).json(updatedThought); } catch (error){ From 515fe066c18f064212e6ef4129feefe4c837f77f Mon Sep 17 00:00:00 2001 From: Gitte Beckmann Date: Tue, 7 Jan 2025 17:32:19 +0100 Subject: [PATCH 26/26] - fixed typo and defined updatedThought object --- server.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/server.js b/server.js index f8de35ad..66a91076 100644 --- a/server.js +++ b/server.js @@ -95,13 +95,14 @@ app.get("/thoughts", async (req, res) => { } // Update hearts count - const newHearts = thought.hearts % 2 ===0 ? thought.hearts +1 : thought.hearts -1; - await Thought.findByIdAndUpdate(id, {hearts: newHearts}, {new: true}); + const newHearts = thought.hearts % 2 === 0 ? thought.hearts +1 : thought.hearts -1; + + const updatedThought = await Thought.findByIdAndUpdate(id, {hearts: newHearts}, {new: true}); res.status(200).json(updatedThought); } catch (error){ console.error("There is an errow by liking the thought", error); - res.status(500).jason({message: "Could not like thought"}) + res.status(500).json({message: "Could not like thought"}) } })