From 32ed946ad792a85a9ef07460161a67ea728de6d1 Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 21 Jan 2026 14:43:38 +0100 Subject: [PATCH 01/34] Adds a filter for ID --- package.json | 1 + server.js | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index bf25bb68..00addae2 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "@babel/preset-env": "^7.16.11", "cors": "^2.8.5", "express": "^4.17.3", + "express-list-endpoints": "^7.1.1", "nodemon": "^3.0.1" } } diff --git a/server.js b/server.js index f47771bd..829f3ac4 100644 --- a/server.js +++ b/server.js @@ -1,5 +1,9 @@ import cors from "cors" import express from "express" +import listEndpoints from "express-list-endpoints" +import thoughtData from "./data.json" with { type: "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,7 +17,37 @@ app.use(express.json()) // Start defining your routes here app.get("/", (req, res) => { - res.send("Hello Technigo!") + const endpoints = listEndpoints(app) + + res.json({ + endpoints: endpoints + }) +}) + +app.get("/thoughts", (req, res) => { + const { hearts } = req.query + + let filteredThoughts = thoughtData + + if (hearts) { + filteredThoughts = filteredThoughts.filter((thought) => { + return thought.hearts > 0 + }) + } + + res.json(filteredThoughts) +}) + +app.get("/thoughts/:id", (req, res) => { + const id = req.params.id + const thought = thoughtData.find((thought) => thought._id === id) + + if (!thought) { + return res + .json({ error: `Thought with id ${id} does not exist` }) + } + + res.json(thought) }) // Start the server From a9264452d826a0cbc617ace234b39049f8101582 Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 21 Jan 2026 14:47:43 +0100 Subject: [PATCH 02/34] Adds filter of thoughts with 0 likes --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 829f3ac4..ab3c8f06 100644 --- a/server.js +++ b/server.js @@ -31,7 +31,7 @@ app.get("/thoughts", (req, res) => { if (hearts) { filteredThoughts = filteredThoughts.filter((thought) => { - return thought.hearts > 0 + return thought.hearts === 0 }) } From 48b2bcbfd0aa7b8bd55d0f65491456347c9ef10b Mon Sep 17 00:00:00 2001 From: Julia Date: Mon, 9 Feb 2026 14:26:56 +0100 Subject: [PATCH 03/34] Troubleshooting --- package.json | 1 + server.js | 174 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 156 insertions(+), 19 deletions(-) diff --git a/package.json b/package.json index 00addae2..214a34f0 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "cors": "^2.8.5", "express": "^4.17.3", "express-list-endpoints": "^7.1.1", + "mongoose": "^9.1.5", "nodemon": "^3.0.1" } } diff --git a/server.js b/server.js index ab3c8f06..6c53e46c 100644 --- a/server.js +++ b/server.js @@ -1,9 +1,24 @@ import cors from "cors" import express from "express" +import mongoose from "mongoose" +import "dotenv/config" import listEndpoints from "express-list-endpoints" import thoughtData from "./data.json" with { type: "json" } +const mongoURL = process.env.MONGO_URL || "mongodb://localhost/thoughts" +mongoose.connect(mongoURL).catch(error => console.error("Mongo connection error:", error)) +if (process.env.RESET_DB === "true") { + const seedDatabase = async () => { + await Thought.deleteMany() + thoughtData.forEach((thought) => { + new Thought(thought).save() + }) + } + + console.log("seeding database") + seedDatabase() +} // 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: @@ -15,39 +30,160 @@ const app = express() app.use(cors()) app.use(express.json()) -// Start defining your routes here -app.get("/", (req, res) => { - const endpoints = listEndpoints(app) - res.json({ - endpoints: endpoints - }) +const thoughtSchema = new mongoose.Schema({ + message: { type: String, required: true }, + hearts: { type: Number, default: 0 }, + createdAt: { type: Date, default: Date.now } +}) + +const Thought = mongoose.model('Thought', thoughtSchema) + +// Start defining your routes here +app.get("/", async (req, res) => { + // const endpoints = listEndpoints(app) + try { + const thoughts = await Thought.find() + res.json(thoughts) + } catch (error) { + console.error(error) + res.status(500).json({ message: "Server error" }) + } }) -app.get("/thoughts", (req, res) => { +app.get("/thoughts", async (req, res) => { const { hearts } = req.query - let filteredThoughts = thoughtData + const dbQuery = {} + if (hearts !== undefined) { + const heartsNum = Number(hearts) + if (!Number.isNaN(heartsNum)) { + dbQuery.hearts = heartsNum + } + } + + try { + const thoughts = await Thought.find(dbQuery) + if (thoughts.length === 0) { + return res.status(404).json({ + success: false, + response: [], + message: "No thoughts match the query" + }) + } - if (hearts) { - filteredThoughts = filteredThoughts.filter((thought) => { - return thought.hearts === 0 + return res.status(200).json({ + success: true, + response: thoughts, + message: "Thoughts retrieved" + }) + } catch (error) { + console.error(error); + return res.status(500).json({ + success: false, + response: [], + message: error }) } - - res.json(filteredThoughts) }) -app.get("/thoughts/:id", (req, res) => { +app.get("/thoughts/:id", async (req, res) => { const id = req.params.id - const thought = thoughtData.find((thought) => thought._id === id) - if (!thought) { - return res - .json({ error: `Thought with id ${id} does not exist` }) + try { + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: null, + message: "Invalid ID format", + + }) + } + const thought = await Thought.findById(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: null, + message: "Thought not found", + }) + } + + return res.status(200).json({ + success: true, + response: thought, + message: "Success", + }) } - res.json(thought) + catch (error) { + return res.status(500).json({ + success: false, + response: null, + message: error, + }) + } +} +) + + +app.post("/thoughts", async (req, res) => { + const { message } = req.body; + + try { + const newThought = await new Thought({ message }).save(); + + if (!newThought) { + return res.status(400).json({ + success: false, + data: null, + message: "Failed to post thought" + }); + } + + res.status(201).json({ + success: true, + data: newThought, + message: "Thought created successfully." + }); + } catch (error) { + res.status(500).json({ + success: false, + data: null, + message: error.message || "Server error" + }); + } +}); + +// Delete +app.delete("/thoughts/:id", async (req, res) => { + const id = req.params.id; + try { + const thought = await Thought.findById(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: [], + message: "Thought not found" + }) + } + + await Thought.findByIdAndDelete(id) + + res.status(200).json({ + success: true, + response: id, + message: "Thought deleted successfully" + }) + + } catch (error) { + res.status(500).json({ + success: false, + response: null, + message: error, + }) + } }) // Start the server From 1613e9b1c7c26b7c30ffc3d2e07efd9e95706c1f Mon Sep 17 00:00:00 2001 From: Julia Date: Mon, 9 Feb 2026 14:57:16 +0100 Subject: [PATCH 04/34] More troubleshooting --- server.js | 162 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 149 insertions(+), 13 deletions(-) diff --git a/server.js b/server.js index 6c53e46c..3221fcdd 100644 --- a/server.js +++ b/server.js @@ -30,28 +30,140 @@ const app = express() app.use(cors()) app.use(express.json()) - +// Thought schema const thoughtSchema = new mongoose.Schema({ message: { type: String, required: true }, hearts: { type: Number, default: 0 }, createdAt: { type: Date, default: Date.now } + // userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true } }) const Thought = mongoose.model('Thought', thoughtSchema) +// User schema +const UserSchema = new mongoose.Schema({ + email: { type: String, required: true, unique: true }, + password: { type: String, required: true }, + accessToken: { type: String } +}) + +const User = mongoose.model('User', UserSchema) + +const authenticateUser = async (req, res, next) => { + try { + const user = await User.findOne({ + accessToken: req.header('Authorization').replace("Bearer ", ""), + }) + if (user) { + req.user = user + next() + } else { + res.status(401).json({ + message: "Authentication missing / invalid", + loggedOut: true + }) + } + } catch (error) { + res.status(500).json({ message: "Internal server error", error: error.message }) + } +} + // Start defining your routes here -app.get("/", async (req, res) => { - // const endpoints = listEndpoints(app) + +// All +app.get("/", (req, res) => { + const endpoints = listEndpoints(app) + res.json({ + message: "Welcome to the happy thoughts API. Here is a list of all endpoints", + endpoints: endpoints, + }) +}) + +// New User +app.post('/users/signup', async (req, res) => { try { - const thoughts = await Thought.find() - res.json(thoughts) + const { email, password } = req.body + + const existingUser = await User.findOne({ + email: email.toLowerCase() + }) + + if (existingUser) { + return res.status(400).json({ + success: false, + message: "User with this email already exists" + }) + } + + const salt = bcrypt.genSaltSync() + const hashedPassword = bcrypt.hashSync(password, salt) + const user = new User({ email, password: hashedPassword }) + + await user.save() + + res.status(200).json({ + success: true, + message: "User created successfully", + response: { + email: user.email, + id: user._id, + accessToken: user.accessToken, + }, + }) + } catch (error) { + res.status(400).json({ + success: false, + message: 'Could not create user', + response: error, + }) + } +}) + +// Sign In +app.post('/users/login', async (req, res) => { + try { + const { email, password } = req.body + const user = await User.findOne({ email: email.toLowerCase() }) + + if (user && bcrypt.compareSync(password, user.password)) { + res.json({ + success: true, + message: "Logged in successfully", + response: { + email: user.email, + id: user._id, + accessToken: user.accessToken + }, + }) + } else { + res.status(401).json({ + success: false, + message: "Wrong e-mail or password", + response: null, + }) + } } catch (error) { - console.error(error) - res.status(500).json({ message: "Server error" }) + res.status(500).json({ + success: false, + message: "Something went wrong", + response: error + }) } }) +// Show all thoughts app.get("/thoughts", async (req, res) => { + try { + const thoughts = await Thought.find().sort({ createdAt: "desc" }) + res.json(thoughts) + + } catch (error) { + res.status(500).json({ error: "Failed to fetch thougts" }) + } +}) + +// Show thoughts with likes +app.get("/thoughts/likes", async (req, res) => { const { hearts } = req.query const dbQuery = {} @@ -87,6 +199,7 @@ app.get("/thoughts", async (req, res) => { } }) +// Filter by ID app.get("/thoughts/:id", async (req, res) => { const id = req.params.id @@ -126,19 +239,19 @@ app.get("/thoughts/:id", async (req, res) => { } ) - +// Post app.post("/thoughts", async (req, res) => { - const { message } = req.body; + const { message } = req.body try { - const newThought = await new Thought({ message }).save(); + const newThought = await new Thought({ message }).save() if (!newThought) { return res.status(400).json({ success: false, data: null, message: "Failed to post thought" - }); + }) } res.status(201).json({ @@ -151,9 +264,32 @@ app.post("/thoughts", async (req, res) => { success: false, data: null, message: error.message || "Server error" - }); + }) } -}); +}) + +// Edit +app.patch('/messages/:id', async (req, res) => { + try { + const thought = await Thought.findById(req.params.id) + + if (!thought) { + return res.status(404).json({ error: "Thought not found" }) + } + + if (thought.userId.toString() !== req.user._id.toString()) { + return res.status(403).json({ error: "You can only edit your own thoughts" }) + } + + thought.thought = req.body.thought || thought.thought + await thought.save() + + res.json(thought) + } catch (error) { + res.status(400).json({ error: "Invalid Id / request" }) + } +}) + // Delete app.delete("/thoughts/:id", async (req, res) => { From 55a9c44ce43cce06b20b3e20c7191a3e638141c2 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 10:26:57 +0100 Subject: [PATCH 05/34] Adds users --- routes/thoughtRoutes.js | 193 ++++++++++++++++++++++++ routes/userRoutes.js | 107 +++++++++++++ server.js | 324 +++------------------------------------- 3 files changed, 321 insertions(+), 303 deletions(-) create mode 100644 routes/thoughtRoutes.js create mode 100644 routes/userRoutes.js diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js new file mode 100644 index 00000000..d7c4f2ca --- /dev/null +++ b/routes/thoughtRoutes.js @@ -0,0 +1,193 @@ +import express from "express" +import mongoose from "mongoose" +import { authenticateUser } from "../middleware/authMiddleware.js" + +const router = express.Router(); + +// Thought schema +const thoughtSchema = new mongoose.Schema({ + message: { type: String, required: true }, + hearts: { type: Number, default: 0 }, + createdAt: { type: Date, default: Date.now }, + userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true } +}) + +const Thought = mongoose.model('Thought', thoughtSchema) + + +// Show all thoughts +app.get("/thoughts", async (req, res) => { + try { + const thoughts = await Thought.find().sort({ createdAt: "desc" }) + res.json(thoughts) + + } catch (error) { + res.status(500).json({ error: "Failed to fetch thougts" }) + } +}) + + +// Show thoughts with likes +router.get("/thoughts/likes", async (req, res) => { + const { hearts } = req.query + + const dbQuery = {} + if (hearts !== undefined) { + const heartsNum = Number(hearts) + if (!Number.isNaN(heartsNum)) { + dbQuery.hearts = heartsNum + } + } + + try { + const thoughts = await Thought.find(dbQuery) + if (thoughts.length === 0) { + return res.status(404).json({ + success: false, + response: [], + message: "No thoughts match the query" + }) + } + + return res.status(200).json({ + success: true, + response: thoughts, + message: "Thoughts retrieved" + }) + } catch (error) { + console.error(error); + return res.status(500).json({ + success: false, + response: [], + message: error + }) + } +}) + +// Filter by ID +app.get("/thoughts/:id", async (req, res) => { + const id = req.params.id + + try { + if (!mongoose.Types.ObjectId.isValid(id)) { + return res.status(400).json({ + success: false, + response: null, + message: "Invalid ID format", + + }) + } + const thought = await Thought.findById(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: null, + message: "Thought not found", + }) + } + + return res.status(200).json({ + success: true, + response: thought, + message: "Success", + }) + } + + catch (error) { + return res.status(500).json({ + success: false, + response: null, + message: error, + }) + } +} +) + + +// Post +app.post("/thoughts", async (req, res) => { + const { message } = req.body + + try { + const newThought = await new Thought({ + message, userId: req.user._id, + }).save() + + if (!newThought) { + return res.status(400).json({ + success: false, + data: null, + message: "Failed to post thought" + }) + } + + res.status(201).json({ + success: true, + data: newThought, + message: "Thought created successfully." + }); + } catch (error) { + res.status(500).json({ + success: false, + data: null, + message: error.message || "Server error" + }) + } +}) + +// Edit +app.patch('/thoughts/:id', async (req, res) => { + try { + const thought = await Thought.findById(req.params.id) + + if (!thought) { + return res.status(404).json({ error: "Thought not found" }) + } + + if (thought.userId.toString() !== req.user._id.toString()) { + return res.status(403).json({ error: "You can only edit your own thoughts" }) + } + + thought.thought = req.body.thought || thought.thought + await thought.save() + + res.json(thought) + } catch (error) { + res.status(400).json({ error: "Invalid Id / request" }) + } +}) + + +// Delete +app.delete("/thoughts/:id", async (req, res) => { + const id = req.params.id; + try { + const thought = await Thought.findById(id) + + if (!thought) { + return res.status(404).json({ + success: false, + response: [], + message: "Thought not found" + }) + } + + await Thought.findByIdAndDelete(id) + + res.status(200).json({ + success: true, + response: id, + message: "Thought deleted successfully" + }) + + } catch (error) { + res.status(500).json({ + success: false, + response: null, + message: error, + }) + } +}) + +export default router diff --git a/routes/userRoutes.js b/routes/userRoutes.js new file mode 100644 index 00000000..bb0fd115 --- /dev/null +++ b/routes/userRoutes.js @@ -0,0 +1,107 @@ +import express from "express" +import bcrypt from "bcrypt" + +const router = express.Router() + +// User schema +const UserSchema = new mongoose.Schema({ + email: { type: String, required: true, unique: true }, + password: { type: String, required: true }, + accessToken: { type: String } +}) + +const User = mongoose.model('User', UserSchema) + + +// New User +app.post('/users/signup', async (req, res) => { + try { + const { email, password } = req.body + + const existingUser = await User.findOne({ + email: email.toLowerCase() + }) + + if (existingUser) { + return res.status(400).json({ + success: false, + message: "User with this email already exists" + }) + } + + const salt = bcrypt.genSaltSync() + const hashedPassword = bcrypt.hashSync(password, salt) + const user = new User({ email, password: hashedPassword }) + + await user.save() + + res.status(200).json({ + success: true, + message: "User created successfully", + response: { + email: user.email, + id: user._id, + accessToken: user.accessToken, + }, + }) + } catch (error) { + res.status(400).json({ + success: false, + message: 'Could not create user', + response: error, + }) + } +}) + +// Log In +app.post('/users/login', async (req, res) => { + try { + const { email, password } = req.body + const user = await User.findOne({ email: email.toLowerCase() }) + + if (user && bcrypt.compareSync(password, user.password)) { + res.json({ + success: true, + message: "Logged in successfully", + response: { + email: user.email, + id: user._id, + accessToken: user.accessToken + }, + }) + } else { + res.status(401).json({ + success: false, + message: "Wrong e-mail or password", + response: null, + }) + } + } catch (error) { + res.status(500).json({ + success: false, + message: "Something went wrong", + response: error + }) + } +}) + +export default router + +// const authenticateUser = async (req, res, next) => { +// try { +// const user = await User.findOne({ +// accessToken: req.header('Authorization').replace("Bearer ", ""), +// }) +// if (user) { +// req.user = user +// next() +// } else { +// res.status(401).json({ +// message: "Authentication missing / invalid", +// loggedOut: true +// }) +// } +// } catch (error) { +// res.status(500).json({ message: "Internal server error", error: error.message }) +// } +// } \ No newline at end of file diff --git a/server.js b/server.js index 3221fcdd..1541c254 100644 --- a/server.js +++ b/server.js @@ -3,9 +3,11 @@ import express from "express" import mongoose from "mongoose" import "dotenv/config" import listEndpoints from "express-list-endpoints" -import thoughtData from "./data.json" with { type: "json" } +// import thoughtData from "./data.json" with { type: "json" } +import thoughtRoutes from "./routes/thoughtRoutes" +import userRoutes from "./routes/userRoutes" -const mongoURL = process.env.MONGO_URL || "mongodb://localhost/thoughts" +const mongoURL = process.env.MONGO_URL mongoose.connect(mongoURL).catch(error => console.error("Mongo connection error:", error)) if (process.env.RESET_DB === "true") { @@ -18,311 +20,27 @@ if (process.env.RESET_DB === "true") { console.log("seeding database") seedDatabase() -} -// 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() + const port = process.env.PORT || 8080 + const app = express() -// Add middlewares to enable cors and json body parsing -app.use(cors()) -app.use(express.json()) + app.use(cors()) + app.use(express.json()) -// Thought schema -const thoughtSchema = new mongoose.Schema({ - message: { type: String, required: true }, - hearts: { type: Number, default: 0 }, - createdAt: { type: Date, default: Date.now } - // userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true } -}) - -const Thought = mongoose.model('Thought', thoughtSchema) - -// User schema -const UserSchema = new mongoose.Schema({ - email: { type: String, required: true, unique: true }, - password: { type: String, required: true }, - accessToken: { type: String } -}) - -const User = mongoose.model('User', UserSchema) - -const authenticateUser = async (req, res, next) => { - try { - const user = await User.findOne({ - accessToken: req.header('Authorization').replace("Bearer ", ""), + // Shows all endpoints + app.get("/", (req, res) => { + const endpoints = listEndpoints(app) + res.json({ + message: "Welcome to the happy thoughts API. Here is a list of all endpoints", + endpoints: endpoints, }) - if (user) { - req.user = user - next() - } else { - res.status(401).json({ - message: "Authentication missing / invalid", - loggedOut: true - }) - } - } catch (error) { - res.status(500).json({ message: "Internal server error", error: error.message }) - } -} - -// Start defining your routes here - -// All -app.get("/", (req, res) => { - const endpoints = listEndpoints(app) - res.json({ - message: "Welcome to the happy thoughts API. Here is a list of all endpoints", - endpoints: endpoints, }) -}) - -// New User -app.post('/users/signup', async (req, res) => { - try { - const { email, password } = req.body - - const existingUser = await User.findOne({ - email: email.toLowerCase() - }) - - if (existingUser) { - return res.status(400).json({ - success: false, - message: "User with this email already exists" - }) - } - - const salt = bcrypt.genSaltSync() - const hashedPassword = bcrypt.hashSync(password, salt) - const user = new User({ email, password: hashedPassword }) - - await user.save() - - res.status(200).json({ - success: true, - message: "User created successfully", - response: { - email: user.email, - id: user._id, - accessToken: user.accessToken, - }, - }) - } catch (error) { - res.status(400).json({ - success: false, - message: 'Could not create user', - response: error, - }) - } -}) - -// Sign In -app.post('/users/login', async (req, res) => { - try { - const { email, password } = req.body - const user = await User.findOne({ email: email.toLowerCase() }) - - if (user && bcrypt.compareSync(password, user.password)) { - res.json({ - success: true, - message: "Logged in successfully", - response: { - email: user.email, - id: user._id, - accessToken: user.accessToken - }, - }) - } else { - res.status(401).json({ - success: false, - message: "Wrong e-mail or password", - response: null, - }) - } - } catch (error) { - res.status(500).json({ - success: false, - message: "Something went wrong", - response: error - }) - } -}) - -// Show all thoughts -app.get("/thoughts", async (req, res) => { - try { - const thoughts = await Thought.find().sort({ createdAt: "desc" }) - res.json(thoughts) - - } catch (error) { - res.status(500).json({ error: "Failed to fetch thougts" }) - } -}) - -// Show thoughts with likes -app.get("/thoughts/likes", async (req, res) => { - const { hearts } = req.query - - const dbQuery = {} - if (hearts !== undefined) { - const heartsNum = Number(hearts) - if (!Number.isNaN(heartsNum)) { - dbQuery.hearts = heartsNum - } - } - - try { - const thoughts = await Thought.find(dbQuery) - if (thoughts.length === 0) { - return res.status(404).json({ - success: false, - response: [], - message: "No thoughts match the query" - }) - } - - return res.status(200).json({ - success: true, - response: thoughts, - message: "Thoughts retrieved" - }) - } catch (error) { - console.error(error); - return res.status(500).json({ - success: false, - response: [], - message: error - }) - } -}) -// Filter by ID -app.get("/thoughts/:id", async (req, res) => { - const id = req.params.id + app.use("/thoughts", thoughtRoutes) + app.use("/users", userRoutes) - try { - if (!mongoose.Types.ObjectId.isValid(id)) { - return res.status(400).json({ - success: false, - response: null, - message: "Invalid ID format", - - }) - } - const thought = await Thought.findById(id) - - if (!thought) { - return res.status(404).json({ - success: false, - response: null, - message: "Thought not found", - }) - } - - return res.status(200).json({ - success: true, - response: thought, - message: "Success", - }) - } - - catch (error) { - return res.status(500).json({ - success: false, - response: null, - message: error, - }) - } -} -) - -// Post -app.post("/thoughts", async (req, res) => { - const { message } = req.body - - try { - const newThought = await new Thought({ message }).save() - - if (!newThought) { - return res.status(400).json({ - success: false, - data: null, - message: "Failed to post thought" - }) - } - - res.status(201).json({ - success: true, - data: newThought, - message: "Thought created successfully." - }); - } catch (error) { - res.status(500).json({ - success: false, - data: null, - message: error.message || "Server error" - }) - } -}) - -// Edit -app.patch('/messages/:id', async (req, res) => { - try { - const thought = await Thought.findById(req.params.id) - - if (!thought) { - return res.status(404).json({ error: "Thought not found" }) - } - - if (thought.userId.toString() !== req.user._id.toString()) { - return res.status(403).json({ error: "You can only edit your own thoughts" }) - } - - thought.thought = req.body.thought || thought.thought - await thought.save() - - res.json(thought) - } catch (error) { - res.status(400).json({ error: "Invalid Id / request" }) - } -}) - - -// Delete -app.delete("/thoughts/:id", async (req, res) => { - const id = req.params.id; - try { - const thought = await Thought.findById(id) - - if (!thought) { - return res.status(404).json({ - success: false, - response: [], - message: "Thought not found" - }) - } - - await Thought.findByIdAndDelete(id) - - res.status(200).json({ - success: true, - response: id, - message: "Thought deleted successfully" - }) - - } catch (error) { - res.status(500).json({ - success: false, - response: null, - message: error, - }) - } -}) - -// Start the server -app.listen(port, () => { - console.log(`Server running on http://localhost:${port}`) -}) + // Start the server + app.listen(port, () => { + console.log(`Server running on http://localhost:${port}`) + }) +} \ No newline at end of file From 04d5efba4a422112deeea645d23774234fa5f6b8 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 10:40:36 +0100 Subject: [PATCH 06/34] Error when deploying --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index 1541c254..5ea6834a 100644 --- a/server.js +++ b/server.js @@ -1,7 +1,7 @@ import cors from "cors" import express from "express" import mongoose from "mongoose" -import "dotenv/config" +// import "dotenv/config" import listEndpoints from "express-list-endpoints" // import thoughtData from "./data.json" with { type: "json" } import thoughtRoutes from "./routes/thoughtRoutes" From dcd0fcc09386bd096aff8c3296d7888298745b61 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 10:42:56 +0100 Subject: [PATCH 07/34] Comments out errors --- routes/thoughtRoutes.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index d7c4f2ca..cbfc504c 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -1,6 +1,6 @@ import express from "express" import mongoose from "mongoose" -import { authenticateUser } from "../middleware/authMiddleware.js" +// import { authenticateUser } from "../middleware/authMiddleware.js" const router = express.Router(); @@ -16,7 +16,7 @@ const Thought = mongoose.model('Thought', thoughtSchema) // Show all thoughts -app.get("/thoughts", async (req, res) => { +router.get("/thoughts", async (req, res) => { try { const thoughts = await Thought.find().sort({ createdAt: "desc" }) res.json(thoughts) @@ -65,7 +65,7 @@ router.get("/thoughts/likes", async (req, res) => { }) // Filter by ID -app.get("/thoughts/:id", async (req, res) => { +router.get("/thoughts/:id", async (req, res) => { const id = req.params.id try { @@ -106,7 +106,7 @@ app.get("/thoughts/:id", async (req, res) => { // Post -app.post("/thoughts", async (req, res) => { +router.post("/thoughts", async (req, res) => { const { message } = req.body try { @@ -137,7 +137,7 @@ app.post("/thoughts", async (req, res) => { }) // Edit -app.patch('/thoughts/:id', async (req, res) => { +router.patch('/thoughts/:id', async (req, res) => { try { const thought = await Thought.findById(req.params.id) @@ -160,7 +160,7 @@ app.patch('/thoughts/:id', async (req, res) => { // Delete -app.delete("/thoughts/:id", async (req, res) => { +router.delete("/thoughts/:id", async (req, res) => { const id = req.params.id; try { const thought = await Thought.findById(id) From ccc290da5482900ed86f1510abf3692f99200d98 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 10:46:01 +0100 Subject: [PATCH 08/34] Adds bcrypt --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 214a34f0..f3e63ae5 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": "^6.0.0", "cors": "^2.8.5", "express": "^4.17.3", "express-list-endpoints": "^7.1.1", From dbe90412a94482b1d6760111206f0f4ce9f659ec Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 11:08:57 +0100 Subject: [PATCH 09/34] Installes mongoose save --- package.json | 2 +- server.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index f3e63ae5..38fc5f7d 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "cors": "^2.8.5", "express": "^4.17.3", "express-list-endpoints": "^7.1.1", - "mongoose": "^9.1.5", + "mongoose": "^9.2.0", "nodemon": "^3.0.1" } } diff --git a/server.js b/server.js index 5ea6834a..f6cca320 100644 --- a/server.js +++ b/server.js @@ -8,7 +8,7 @@ import thoughtRoutes from "./routes/thoughtRoutes" import userRoutes from "./routes/userRoutes" const mongoURL = process.env.MONGO_URL -mongoose.connect(mongoURL).catch(error => console.error("Mongo connection error:", error)) +mongoose.connect(mongoUrl) if (process.env.RESET_DB === "true") { const seedDatabase = async () => { From 3f0b6c0c8fecec2cfc7fb2e297a7518401e7f6ef Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 11:14:18 +0100 Subject: [PATCH 10/34] Add mongoose dependency --- server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server.js b/server.js index f6cca320..6e0d51a9 100644 --- a/server.js +++ b/server.js @@ -1,6 +1,6 @@ import cors from "cors" import express from "express" -import mongoose from "mongoose" +import mongoose from 'mongoose' // import "dotenv/config" import listEndpoints from "express-list-endpoints" // import thoughtData from "./data.json" with { type: "json" } From ac8f163677b9921088393140424cd745b3109a82 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 11:15:41 +0100 Subject: [PATCH 11/34] Troubleshooting again --- server.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server.js b/server.js index 6e0d51a9..6af071b0 100644 --- a/server.js +++ b/server.js @@ -7,6 +7,8 @@ import listEndpoints from "express-list-endpoints" import thoughtRoutes from "./routes/thoughtRoutes" import userRoutes from "./routes/userRoutes" +const mongoose = require('mongoose') + const mongoURL = process.env.MONGO_URL mongoose.connect(mongoUrl) From 66444aaffd3a5cff219b1ede3dfb969bcfcacb73 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 11:22:28 +0100 Subject: [PATCH 12/34] More troubleshooting --- server.js | 1 - 1 file changed, 1 deletion(-) diff --git a/server.js b/server.js index 6af071b0..2bec31fb 100644 --- a/server.js +++ b/server.js @@ -1,6 +1,5 @@ import cors from "cors" import express from "express" -import mongoose from 'mongoose' // import "dotenv/config" import listEndpoints from "express-list-endpoints" // import thoughtData from "./data.json" with { type: "json" } From d4b1da0bfb177ceee09ec2304d8a7c4cb6569d4f Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 11:28:41 +0100 Subject: [PATCH 13/34] Tried fixing with the AI of render --- server.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server.js b/server.js index 2bec31fb..f6cca320 100644 --- a/server.js +++ b/server.js @@ -1,13 +1,12 @@ import cors from "cors" import express from "express" +import mongoose from "mongoose" // import "dotenv/config" import listEndpoints from "express-list-endpoints" // import thoughtData from "./data.json" with { type: "json" } import thoughtRoutes from "./routes/thoughtRoutes" import userRoutes from "./routes/userRoutes" -const mongoose = require('mongoose') - const mongoURL = process.env.MONGO_URL mongoose.connect(mongoUrl) From 03bcb12c78b4cc8aba264ea82bb6c37205410c37 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 11:38:13 +0100 Subject: [PATCH 14/34] Adds mongoose in user route --- routes/userRoutes.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/routes/userRoutes.js b/routes/userRoutes.js index bb0fd115..22ab699f 100644 --- a/routes/userRoutes.js +++ b/routes/userRoutes.js @@ -1,5 +1,6 @@ import express from "express" import bcrypt from "bcrypt" +import mongoose from "mongoose" const router = express.Router() @@ -14,7 +15,7 @@ const User = mongoose.model('User', UserSchema) // New User -app.post('/users/signup', async (req, res) => { +router.post('/users/signup', async (req, res) => { try { const { email, password } = req.body @@ -54,7 +55,7 @@ app.post('/users/signup', async (req, res) => { }) // Log In -app.post('/users/login', async (req, res) => { +router.post('/users/login', async (req, res) => { try { const { email, password } = req.body const user = await User.findOne({ email: email.toLowerCase() }) From 845efa4c724dcbeab22c48a22b718526fc323241 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 12:05:44 +0100 Subject: [PATCH 15/34] Adds .env --- server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index f6cca320..7b9f2b23 100644 --- a/server.js +++ b/server.js @@ -1,13 +1,13 @@ import cors from "cors" import express from "express" import mongoose from "mongoose" -// import "dotenv/config" +import "dotenv/config" import listEndpoints from "express-list-endpoints" // import thoughtData from "./data.json" with { type: "json" } import thoughtRoutes from "./routes/thoughtRoutes" import userRoutes from "./routes/userRoutes" -const mongoURL = process.env.MONGO_URL +const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) if (process.env.RESET_DB === "true") { From 895ad54615b1e6b5c2987b9e6410d56c7ea90b56 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 12:16:23 +0100 Subject: [PATCH 16/34] Adds dotenv --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 38fc5f7d..bf80b97e 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "@babel/preset-env": "^7.16.11", "bcrypt": "^6.0.0", "cors": "^2.8.5", + "dotenv": "^17.2.4", "express": "^4.17.3", "express-list-endpoints": "^7.1.1", "mongoose": "^9.2.0", From 9a9be3757b437e84dbd4c16cf175193a4f1b5f92 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 12:42:05 +0100 Subject: [PATCH 17/34] Error message: cant find open port --- routes/thoughtRoutes.js | 2 +- server.js | 60 ++++++++++++++++++++--------------------- 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index cbfc504c..df7983f8 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -190,4 +190,4 @@ router.delete("/thoughts/:id", async (req, res) => { } }) -export default router +export default router \ No newline at end of file diff --git a/server.js b/server.js index 7b9f2b23..c21daee5 100644 --- a/server.js +++ b/server.js @@ -10,37 +10,37 @@ import userRoutes from "./routes/userRoutes" const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) -if (process.env.RESET_DB === "true") { - const seedDatabase = async () => { - await Thought.deleteMany() - thoughtData.forEach((thought) => { - new Thought(thought).save() - }) - } - - console.log("seeding database") - seedDatabase() - - const port = process.env.PORT || 8080 - const app = express() - - app.use(cors()) - app.use(express.json()) - - // Shows all endpoints - app.get("/", (req, res) => { - const endpoints = listEndpoints(app) - res.json({ - message: "Welcome to the happy thoughts API. Here is a list of all endpoints", - endpoints: endpoints, - }) +// if (process.env.RESET_DB === "true") { +// const seedDatabase = async () => { +// await Thought.deleteMany() +// thoughtData.forEach((thought) => { +// new Thought(thought).save() +// }) +// } + +// console.log("seeding database") +// seedDatabase() + +const app = express() + +app.use(cors()) +app.use(express.json()) + +// Shows all endpoints +app.get("/", (req, res) => { + const endpoints = listEndpoints(app) + res.json({ + message: "Welcome to the happy thoughts API. Here is a list of all endpoints", + endpoints: endpoints, }) +}) - app.use("/thoughts", thoughtRoutes) - app.use("/users", userRoutes) +app.use("/thoughts", thoughtRoutes) +app.use("/users", userRoutes) - // Start the server - app.listen(port, () => { - console.log(`Server running on http://localhost:${port}`) - }) +const port = process.env.PORT || 8080 +// Start the server +app.listen(port, () => { + console.log(`Server running on http://localhost:${port}`) +}) } \ No newline at end of file From d8c2a888d4579fc3395f90d0e9907b0f900e1695 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 12:47:49 +0100 Subject: [PATCH 18/34] Removes consolelog --- server.js | 60 +++++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/server.js b/server.js index c21daee5..f02c7892 100644 --- a/server.js +++ b/server.js @@ -10,37 +10,37 @@ import userRoutes from "./routes/userRoutes" const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) -// if (process.env.RESET_DB === "true") { -// const seedDatabase = async () => { -// await Thought.deleteMany() -// thoughtData.forEach((thought) => { -// new Thought(thought).save() -// }) -// } - -// console.log("seeding database") -// seedDatabase() - -const app = express() - -app.use(cors()) -app.use(express.json()) - -// Shows all endpoints -app.get("/", (req, res) => { - const endpoints = listEndpoints(app) - res.json({ - message: "Welcome to the happy thoughts API. Here is a list of all endpoints", - endpoints: endpoints, +if (process.env.RESET_DB === "true") { + const seedDatabase = async () => { + await Thought.deleteMany() + thoughtData.forEach((thought) => { + new Thought(thought).save() + }) + } + + console.log("seeding database") + await seedDatabase() + + const app = express() + + app.use(cors()) + app.use(express.json()) + + // Shows all endpoints + app.get("/", (req, res) => { + const endpoints = listEndpoints(app) + res.json({ + message: "Welcome to the happy thoughts API. Here is a list of all endpoints", + endpoints: endpoints, + }) }) -}) -app.use("/thoughts", thoughtRoutes) -app.use("/users", userRoutes) + app.use("/thoughts", thoughtRoutes) + app.use("/users", userRoutes) -const port = process.env.PORT || 8080 -// Start the server -app.listen(port, () => { - console.log(`Server running on http://localhost:${port}`) -}) + const port = process.env.PORT || 8080 + // Start the server + app.listen(port, () => { + // console.log(`Server running on http://localhost:${port}`) + }) } \ No newline at end of file From fe61e991d52812674a5c33527434736260d6940f Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 12:53:02 +0100 Subject: [PATCH 19/34] Adds .js --- server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index f02c7892..a8be89cd 100644 --- a/server.js +++ b/server.js @@ -4,8 +4,8 @@ import mongoose from "mongoose" import "dotenv/config" import listEndpoints from "express-list-endpoints" // import thoughtData from "./data.json" with { type: "json" } -import thoughtRoutes from "./routes/thoughtRoutes" -import userRoutes from "./routes/userRoutes" +import thoughtRoutes from "./routes/thoughtRoutes.js" +import userRoutes from "./routes/userRoutes.js" const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) From 1113758abbe8aefd95b578772c85901fde55d563 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 15:37:50 +0100 Subject: [PATCH 20/34] Adds type field in json --- package.json | 3 ++- server.js | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index bf80b97e..86f79bfb 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "project-api", "version": "1.0.0", "description": "Project API", + "type": "module", "scripts": { "start": "babel-node server.js", "dev": "nodemon server.js --exec babel-node" @@ -20,4 +21,4 @@ "mongoose": "^9.2.0", "nodemon": "^3.0.1" } -} +} \ No newline at end of file diff --git a/server.js b/server.js index a8be89cd..62c32616 100644 --- a/server.js +++ b/server.js @@ -3,12 +3,13 @@ import express from "express" import mongoose from "mongoose" import "dotenv/config" import listEndpoints from "express-list-endpoints" -// import thoughtData from "./data.json" with { type: "json" } +import thoughtData from "./data.json" with { type: "json" } import thoughtRoutes from "./routes/thoughtRoutes.js" import userRoutes from "./routes/userRoutes.js" const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) +mongoose.Promise = Promise if (process.env.RESET_DB === "true") { const seedDatabase = async () => { From d474dc5a525248c661bb36202f11807a4d89b2bf Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 17:24:14 +0100 Subject: [PATCH 21/34] Tries to move a curlybracket --- server.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/server.js b/server.js index 62c32616..0133d3a2 100644 --- a/server.js +++ b/server.js @@ -17,10 +17,10 @@ if (process.env.RESET_DB === "true") { thoughtData.forEach((thought) => { new Thought(thought).save() }) - } - console.log("seeding database") - await seedDatabase() + console.log("seeding database") + await seedDatabase() + } const app = express() @@ -42,6 +42,8 @@ if (process.env.RESET_DB === "true") { const port = process.env.PORT || 8080 // Start the server app.listen(port, () => { - // console.log(`Server running on http://localhost:${port}`) + console.log(`Server running on http://localhost:${port}`) }) -} \ No newline at end of file +} + +export default app \ No newline at end of file From 3ab1cb95fc2114ac2d59d588e5a844cdf3f11819 Mon Sep 17 00:00:00 2001 From: Julia Date: Tue, 10 Feb 2026 17:27:38 +0100 Subject: [PATCH 22/34] Removed an experimental const --- server.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/server.js b/server.js index 0133d3a2..439f6fc0 100644 --- a/server.js +++ b/server.js @@ -44,6 +44,4 @@ if (process.env.RESET_DB === "true") { app.listen(port, () => { console.log(`Server running on http://localhost:${port}`) }) -} - -export default app \ No newline at end of file +} \ No newline at end of file From 55bda579d527600853fb89b2811e129ae2f93c67 Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 12:29:09 +0100 Subject: [PATCH 23/34] Removes reset --- server.js | 61 +++++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/server.js b/server.js index 439f6fc0..7cbf77aa 100644 --- a/server.js +++ b/server.js @@ -11,37 +11,36 @@ const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) mongoose.Promise = Promise -if (process.env.RESET_DB === "true") { - const seedDatabase = async () => { - await Thought.deleteMany() - thoughtData.forEach((thought) => { - new Thought(thought).save() - }) - - console.log("seeding database") - await seedDatabase() - } - - const app = express() - - app.use(cors()) - app.use(express.json()) - - // Shows all endpoints - app.get("/", (req, res) => { - const endpoints = listEndpoints(app) - res.json({ - message: "Welcome to the happy thoughts API. Here is a list of all endpoints", - endpoints: endpoints, - }) +// if (process.env.RESET_DB === "true") { +// const seedDatabase = async () => { +// await Thought.deleteMany() +// thoughtData.forEach((thought) => { +// new Thought(thought).save() +// }) + +// console.log("seeding database") +// await seedDatabase() +// } + +const app = express() + +app.use(cors()) +app.use(express.json()) + +// Shows all endpoints +app.get("/", (req, res) => { + const endpoints = listEndpoints(app) + res.json({ + message: "Welcome to the happy thoughts API. Here is a list of all endpoints", + endpoints: endpoints, }) +}) - app.use("/thoughts", thoughtRoutes) - app.use("/users", userRoutes) +app.use("/thoughts", thoughtRoutes) +app.use("/users", userRoutes) - const port = process.env.PORT || 8080 - // Start the server - app.listen(port, () => { - console.log(`Server running on http://localhost:${port}`) - }) -} \ No newline at end of file +const port = process.env.PORT || 8080 +// Start the server +app.listen(port, () => { + console.log(`Server running on http://localhost:${port}`) +}) From ee39005f24e57c7f6ee06d054194486c0e3f492b Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 12:39:53 +0100 Subject: [PATCH 24/34] Closes the if-statment earlier --- server.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/server.js b/server.js index 7cbf77aa..aed791d0 100644 --- a/server.js +++ b/server.js @@ -11,16 +11,17 @@ const mongoUrl = process.env.MONGO_URL mongoose.connect(mongoUrl) mongoose.Promise = Promise -// if (process.env.RESET_DB === "true") { -// const seedDatabase = async () => { -// await Thought.deleteMany() -// thoughtData.forEach((thought) => { -// new Thought(thought).save() -// }) - -// console.log("seeding database") -// await seedDatabase() -// } +if (process.env.RESET_DB === "true") { + const seedDatabase = async () => { + await Thought.deleteMany() + thoughtData.forEach((thought) => { + new Thought(thought).save() + }) + } + + console.log("seeding database") + await seedDatabase() +} const app = express() From 84a90d672c8e4dc822291e68d8946607c24624ac Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 12:52:00 +0100 Subject: [PATCH 25/34] Removes one /thougths --- server.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.js b/server.js index aed791d0..a5688029 100644 --- a/server.js +++ b/server.js @@ -37,8 +37,8 @@ app.get("/", (req, res) => { }) }) -app.use("/thoughts", thoughtRoutes) -app.use("/users", userRoutes) +app.use("/", thoughtRoutes) +app.use("/", userRoutes) const port = process.env.PORT || 8080 // Start the server From b415baf17cdbc1b74c06c78be276ef704a3baf9f Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 16:48:55 +0100 Subject: [PATCH 26/34] Adds accesstoken --- routes/thoughtRoutes.js | 28 +++++++++++++++++++++++++--- routes/userRoutes.js | 28 ++++++---------------------- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index df7983f8..55636b54 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -1,6 +1,6 @@ import express from "express" import mongoose from "mongoose" -// import { authenticateUser } from "../middleware/authMiddleware.js" +import { User } from "./userRoutes" const router = express.Router(); @@ -107,6 +107,7 @@ router.get("/thoughts/:id", async (req, res) => { // Post router.post("/thoughts", async (req, res) => { + await authenticateUser(req, res, next) const { message } = req.body try { @@ -138,6 +139,7 @@ router.post("/thoughts", async (req, res) => { // Edit router.patch('/thoughts/:id', async (req, res) => { + await authenticateUser(req, res, next) try { const thought = await Thought.findById(req.params.id) @@ -160,7 +162,8 @@ router.patch('/thoughts/:id', async (req, res) => { // Delete -router.delete("/thoughts/:id", async (req, res) => { +router.delete("/thoughts/:id", async (req, res, next) => { + await authenticateUser(req, res, next) const id = req.params.id; try { const thought = await Thought.findById(id) @@ -190,4 +193,23 @@ router.delete("/thoughts/:id", async (req, res) => { } }) -export default router \ No newline at end of file +export default router + +const authenticateUser = async (req, res, next) => { + try { + const user = await User.findOne({ + accessToken: req.header('Authorization').replace("Bearer ", ""), + }) + if (user) { + req.user = user + next() + } else { + res.status(401).json({ + message: "Authentication missing / invalid", + loggedOut: true + }) + } + } catch (error) { + res.status(500).json({ message: "Internal server error", error: error.message }) + } +} \ No newline at end of file diff --git a/routes/userRoutes.js b/routes/userRoutes.js index 22ab699f..f8b9d4b7 100644 --- a/routes/userRoutes.js +++ b/routes/userRoutes.js @@ -8,10 +8,13 @@ const router = express.Router() const UserSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true }, - accessToken: { type: String } + accessToken: { + type: String, + default: () => crypto.randomBytes(128).toString("hex"), + }, }) -const User = mongoose.model('User', UserSchema) +export const User = mongoose.model('User', UserSchema) // New User @@ -86,23 +89,4 @@ router.post('/users/login', async (req, res) => { } }) -export default router - -// const authenticateUser = async (req, res, next) => { -// try { -// const user = await User.findOne({ -// accessToken: req.header('Authorization').replace("Bearer ", ""), -// }) -// if (user) { -// req.user = user -// next() -// } else { -// res.status(401).json({ -// message: "Authentication missing / invalid", -// loggedOut: true -// }) -// } -// } catch (error) { -// res.status(500).json({ message: "Internal server error", error: error.message }) -// } -// } \ No newline at end of file +export default router \ No newline at end of file From 9b1389d171c8b996a5b68290fb430629f62ada1f Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 16:50:35 +0100 Subject: [PATCH 27/34] Adds .js --- routes/thoughtRoutes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index 55636b54..2feca335 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -1,6 +1,6 @@ import express from "express" import mongoose from "mongoose" -import { User } from "./userRoutes" +import { User } from "./userRoutes.js" const router = express.Router(); From dc0ff8030ebd9a4c027ed093c4eaee1092fe4ebe Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 17:37:59 +0100 Subject: [PATCH 28/34] Changes the like endpoint --- routes/thoughtRoutes.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index 2feca335..6af76df5 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -4,6 +4,7 @@ import { User } from "./userRoutes.js" const router = express.Router(); + // Thought schema const thoughtSchema = new mongoose.Schema({ message: { type: String, required: true }, @@ -17,6 +18,7 @@ const Thought = mongoose.model('Thought', thoughtSchema) // Show all thoughts router.get("/thoughts", async (req, res) => { + gi try { const thoughts = await Thought.find().sort({ createdAt: "desc" }) res.json(thoughts) @@ -28,7 +30,7 @@ router.get("/thoughts", async (req, res) => { // Show thoughts with likes -router.get("/thoughts/likes", async (req, res) => { +router.get("/thoughts/:id/like", async (req, res) => { const { hearts } = req.query const dbQuery = {} @@ -64,6 +66,7 @@ router.get("/thoughts/likes", async (req, res) => { } }) + // Filter by ID router.get("/thoughts/:id", async (req, res) => { const id = req.params.id @@ -137,6 +140,7 @@ router.post("/thoughts", async (req, res) => { } }) + // Edit router.patch('/thoughts/:id', async (req, res) => { await authenticateUser(req, res, next) From d8bb25a09fefd9076befa93f7fe411b89de7aa97 Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 18:01:53 +0100 Subject: [PATCH 29/34] Adds likes --- routes/thoughtRoutes.js | 99 +++++++++++++++++++++++++++-------------- 1 file changed, 65 insertions(+), 34 deletions(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index 6af76df5..2d38507f 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -4,6 +4,24 @@ import { User } from "./userRoutes.js" const router = express.Router(); +const authenticateUser = async (req, res, next) => { + try { + const user = await User.findOne({ + accessToken: req.header('Authorization').replace("Bearer ", ""), + }) + if (user) { + req.user = user + next() + } else { + res.status(401).json({ + message: "Authentication missing / invalid", + loggedOut: true + }) + } + } catch (error) { + res.status(500).json({ message: "Internal server error", error: error.message }) + } +} // Thought schema const thoughtSchema = new mongoose.Schema({ @@ -30,7 +48,7 @@ router.get("/thoughts", async (req, res) => { // Show thoughts with likes -router.get("/thoughts/:id/like", async (req, res) => { +router.get("/thoughts/like", async (req, res) => { const { hearts } = req.query const dbQuery = {} @@ -119,11 +137,9 @@ router.post("/thoughts", async (req, res) => { }).save() if (!newThought) { - return res.status(400).json({ - success: false, - data: null, - message: "Failed to post thought" - }) + return res + .status(400) + .json({ success: false, data: null, message: "Failed to post thought" }) } res.status(201).json({ @@ -144,23 +160,57 @@ router.post("/thoughts", async (req, res) => { // Edit router.patch('/thoughts/:id', async (req, res) => { await authenticateUser(req, res, next) - try { - const thought = await Thought.findById(req.params.id) + const { id } = req.params + try { + const thought = await Thought.findById(id); if (!thought) { - return res.status(404).json({ error: "Thought not found" }) + return res.status(404).json({ error: "Thought not found" }); } - if (thought.userId.toString() !== req.user._id.toString()) { - return res.status(403).json({ error: "You can only edit your own thoughts" }) + return res.status(403).json({ error: "You can only edit your own thoughts" }); + } + + thought.message = req.body.message ?? thought.message; + thought.hearts = req.body.hearts ?? thought.hearts; + await thought.save(); + + return res.json({ success: true, thought }); + } catch (err) { + return res.status(400).json({ error: "Invalid request", details: err.message }); + } +}) + + +// Like +router.post("/thoughts/:id/like", async (req, res, next) => { + const { id } = req.params + + if (!mongoose.Types.ObjectId.isValid(id)) { + return res + .status(400) + .json({ success: false, message: "Invalid thought ID" }) + } + + try { + const thought = await Thought.findById(id) + if (!thought) { + return res + .status(404) + .json({ success: false, message: "Thought not found" }) } - thought.thought = req.body.thought || thought.thought + thought.hearts += 1 await thought.save() - res.json(thought) - } catch (error) { - res.status(400).json({ error: "Invalid Id / request" }) + return res + .status(200) + .json({ success: true, hearts: thought.hearts, message: "Liked!" }) + } catch (err) { + console.error(err) + return res + .status(500) + .json({ success: false, message: err.message }) } }) @@ -198,22 +248,3 @@ router.delete("/thoughts/:id", async (req, res, next) => { }) export default router - -const authenticateUser = async (req, res, next) => { - try { - const user = await User.findOne({ - accessToken: req.header('Authorization').replace("Bearer ", ""), - }) - if (user) { - req.user = user - next() - } else { - res.status(401).json({ - message: "Authentication missing / invalid", - loggedOut: true - }) - } - } catch (error) { - res.status(500).json({ message: "Internal server error", error: error.message }) - } -} \ No newline at end of file From dff0038f3ed358b3ebd68cd57810a156ac66289a Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 18:11:34 +0100 Subject: [PATCH 30/34] Installed cors --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 86f79bfb..dc60ca8a 100644 --- a/package.json +++ b/package.json @@ -14,11 +14,11 @@ "@babel/node": "^7.16.8", "@babel/preset-env": "^7.16.11", "bcrypt": "^6.0.0", - "cors": "^2.8.5", + "cors": "^2.8.6", "dotenv": "^17.2.4", "express": "^4.17.3", "express-list-endpoints": "^7.1.1", "mongoose": "^9.2.0", "nodemon": "^3.0.1" } -} \ No newline at end of file +} From fd8e4959e2036391ee51a8279fe82cbcdc14ff90 Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 20:23:58 +0100 Subject: [PATCH 31/34] Adds corsfix --- server.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index a5688029..78d03f5c 100644 --- a/server.js +++ b/server.js @@ -25,7 +25,23 @@ if (process.env.RESET_DB === "true") { const app = express() -app.use(cors()) +const allowedOrigins = [ + "http://localhost:5173", +] + +app.use( + cors({ + origin: (origin, callback) => { + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true) + } else { + callback(new Error("Not allowed by CORS")) + } + }, + credentials: true, + }) +) + app.use(express.json()) // Shows all endpoints From 688a4cbc98cd7a9a15dce9b70414eca92aeda47a Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 20:28:15 +0100 Subject: [PATCH 32/34] Removes cors --- server.js | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/server.js b/server.js index 78d03f5c..a0b3d4ec 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/config" @@ -25,22 +25,22 @@ if (process.env.RESET_DB === "true") { const app = express() -const allowedOrigins = [ - "http://localhost:5173", -] - -app.use( - cors({ - origin: (origin, callback) => { - if (!origin || allowedOrigins.includes(origin)) { - callback(null, true) - } else { - callback(new Error("Not allowed by CORS")) - } - }, - credentials: true, - }) -) +// const allowedOrigins = [ +// "http://localhost:5173", +// ] + +// app.use( +// cors({ +// origin: (origin, callback) => { +// if (!origin || allowedOrigins.includes(origin)) { +// callback(null, true) +// } else { +// callback(new Error("Not allowed by CORS")) +// } +// }, +// credentials: true, +// }) +// ) app.use(express.json()) From 2d24f5d1be287d587d0faea9830df5bab9f501d5 Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 20:32:53 +0100 Subject: [PATCH 33/34] Adds allow all corse --- server.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index a0b3d4ec..b63de6f0 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/config" @@ -24,6 +24,7 @@ if (process.env.RESET_DB === "true") { } const app = express() +app.use(cors({ origin: "*" })) // const allowedOrigins = [ // "http://localhost:5173", From 1c58c75ad0a4b34f9935cd5e0d3f4435332ee1fd Mon Sep 17 00:00:00 2001 From: Julia Date: Wed, 11 Feb 2026 22:28:34 +0100 Subject: [PATCH 34/34] Fixed a few of the final problems --- routes/thoughtRoutes.js | 16 +++++++--------- routes/userRoutes.js | 1 + 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/routes/thoughtRoutes.js b/routes/thoughtRoutes.js index 2d38507f..b6018bba 100644 --- a/routes/thoughtRoutes.js +++ b/routes/thoughtRoutes.js @@ -36,7 +36,6 @@ const Thought = mongoose.model('Thought', thoughtSchema) // Show all thoughts router.get("/thoughts", async (req, res) => { - gi try { const thoughts = await Thought.find().sort({ createdAt: "desc" }) res.json(thoughts) @@ -127,8 +126,7 @@ router.get("/thoughts/:id", async (req, res) => { // Post -router.post("/thoughts", async (req, res) => { - await authenticateUser(req, res, next) +router.post("/thoughts", authenticateUser, async (req, res) => { const { message } = req.body try { @@ -146,8 +144,10 @@ router.post("/thoughts", async (req, res) => { success: true, data: newThought, message: "Thought created successfully." - }); + }) + } catch (error) { + console.log(error) res.status(500).json({ success: false, data: null, @@ -158,8 +158,7 @@ router.post("/thoughts", async (req, res) => { // Edit -router.patch('/thoughts/:id', async (req, res) => { - await authenticateUser(req, res, next) +router.patch('/thoughts/:id', authenticateUser, async (req, res) => { const { id } = req.params try { @@ -183,7 +182,7 @@ router.patch('/thoughts/:id', async (req, res) => { // Like -router.post("/thoughts/:id/like", async (req, res, next) => { +router.post("/thoughts/:id/like", authenticateUser, async (req, res) => { const { id } = req.params if (!mongoose.Types.ObjectId.isValid(id)) { @@ -216,8 +215,7 @@ router.post("/thoughts/:id/like", async (req, res, next) => { // Delete -router.delete("/thoughts/:id", async (req, res, next) => { - await authenticateUser(req, res, next) +router.delete("/thoughts/:id", authenticateUser, async (req, res) => { const id = req.params.id; try { const thought = await Thought.findById(id) diff --git a/routes/userRoutes.js b/routes/userRoutes.js index f8b9d4b7..57959d95 100644 --- a/routes/userRoutes.js +++ b/routes/userRoutes.js @@ -1,5 +1,6 @@ import express from "express" import bcrypt from "bcrypt" +import crypto from "crypto" import mongoose from "mongoose" const router = express.Router()