Skip to content
Open
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
b4b9c99
installed dependencies
alex91-html Jun 4, 2025
dd0fcb9
getting
alex91-html Jun 4, 2025
cf51668
getting data by id problem solved
alex91-html Jun 4, 2025
412a63b
trying to fix crash
alex91-html Jun 4, 2025
b01328d
trying to fix crash
alex91-html Jun 4, 2025
218ed2d
added to do md
alex91-html Jun 4, 2025
1de4fa5
intalled mongoose
alex91-html Jun 6, 2025
f91e126
mongo URL'
alex91-html Jun 6, 2025
f72a39f
mongoose.connect(mongoUrl)
alex91-html Jun 6, 2025
c1d33de
Schema added
alex91-html Jun 6, 2025
8dcfc30
added model
alex91-html Jun 6, 2025
222d15d
updating mongoose
alex91-html Jun 6, 2025
9b45099
deployed
alex91-html Jun 9, 2025
cd5aa31
updated to do list
alex91-html Jun 12, 2025
33ef28a
fixing problem api
alex91-html Jun 12, 2025
102ddea
trying to debugg
alex91-html Jun 13, 2025
0e5ee01
fixed bugs but liking and posting still not working
alex91-html Jun 16, 2025
c5a218e
fixes posting new thought, have to fix edit, save and cancel and liking
alex91-html Jun 16, 2025
961ffee
changes to the front end
alex91-html Jun 16, 2025
5623121
added authentication
alex91-html Jun 16, 2025
0c7ba1f
added folders: endpoints, middleware, models
alex91-html Jun 16, 2025
f680318
moved schema
alex91-html Jun 16, 2025
bf4c068
testing with hout userID
alex91-html Jun 18, 2025
0e4be3d
debugging
alex91-html Jun 18, 2025
394b5ef
debugged
alex91-html Jun 19, 2025
e10fc7e
updated to do list
alex91-html Jun 24, 2025
35d33d2
implementing user.js with user model
alex91-html Jun 24, 2025
cd0507c
installaed bcrypt
alex91-html Jun 24, 2025
f36a797
final
alex91-html Jun 24, 2025
b7c0b25
removed email
alex91-html Jun 24, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 0 additions & 121 deletions data.json

This file was deleted.

Empty file added middleware/authMiddleware.js
Empty file.
22 changes: 22 additions & 0 deletions models/Thought.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import mongoose, { Schema } from "mongoose";

const thoughtSchema = new mongoose.Schema({
message: {
type: String,
required: true,
minLength: 5,
maxLength: 140,
},
hearts: {
type: Number,
default: 0,
min: 0,
},
createdAt: {
type: Date,
default: Date.now,
},
});

export const Thought = mongoose.model("Thought", thoughtSchema);

Empty file added models/user.js
Empty file.
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"dotenv": "^16.5.0",
"express": "^4.17.3",
"nodemon": "^3.0.1"
"express-list-endpoints": "^7.1.1",
"mongodb": "^6.17.0",
"mongoose": "^8.15.1",
"nodemon": "^3.1.10"
}
}
}
156 changes: 141 additions & 15 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,148 @@
import cors from "cors"
import express from "express"
import cors from "cors";
import express from "express";
import listEndpoints from "express-list-endpoints";

// 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()
import mongoose from "mongoose";
import dotenv from "dotenv";
import { Thought } from "./models/Thought.js"; // Adjust the import path as necessary

// Add middlewares to enable cors and json body parsing
app.use(cors())
app.use(express.json())
dotenv.config();

// Start defining your routes here
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost:27017/happy-thoughts-api";
mongoose.connect(mongoUrl);

mongoose.connection.on("error", (error) => {
console.error("MongoDB connection error:", error);
});

mongoose.connection.once("open", () => {
console.log("Connected to MongoDB");
});

const port = process.env.PORT || 8080;
const app = express();

app.use(cors());
app.use(express.json());


// Endpoint to get API documentation
app.get("/", (req, res) => {
res.send("Hello Technigo!")
})
res.json(listEndpoints(app));
});


// Endpoint to get all thoughts
app.get("/thoughts", async (req, res) => {
try {
const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice that you use limit() to limit the number of messages that is sent. Would be nice to add this as a query param as well, then the user/frontend can request how many messages they will recieve in the fetch

res.status(200).json(thoughts);
} catch (error) {
res.status(500).json({ error: "Failed to fetch thoughts", details: error.message });
}
});

// Endpoint to create a new thought
app.post("/thoughts", async (req, res) => {
const { message } = req.body;

if (!message || message.length < 5 || message.length > 140) {
return res.status(400).json({ error: "Message must be between 5 and 140 characters" });
}

try {
console.log("Creating new thought:", message);
const newThought = await new Thought({ message }).save();
res.status(201).json(newThought);
} catch (error) {
res.status(500).json({ error: "Failed to create thought", details: error.message });
}
});

// Endpoint to like a thought
app.post("/thoughts/:id/like", async (req, res) => {
const { id } = req.params;

try {
const updatedThought = await Thought.findByIdAndUpdate(
id,
{ $inc: { hearts: 1 } }, // Increment the hearts count

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice with the increment function

{ new: true } // Return the updated document
);

if (!updatedThought) {
return res.status(404).json({ error: "Thought not found" });
}

res.status(200).json(updatedThought);
} catch (error) {
res.status(500).json({ error: "Failed to like the thought", details: error.message });
}
});

// Endpoint to delete a thought
app.delete("/thoughts/:id", async (req, res) => {
const { id } = req.params;

try {
const deletedThought = await Thought.findByIdAndDelete(id); // No user association

if (!deletedThought) {
return res.status(404).json({ error: "Thought not found" });
}

res.status(200).json({ message: "Thought deleted successfully" });
} catch (error) {
res.status(500).json({ error: "Failed to delete thought", details: error.message });
}
});

// Endpoint to get a single thought by ID
app.get("/thoughts/:id", async (req, res) => {
const { id } = req.params;

try {
const thought = await Thought.findById(id);

if (!thought) {
return res.status(404).json({ error: "Thought not found" });
}

res.status(200).json(thought);
} catch (error) {
res.status(500).json({ error: "Failed to fetch the thought", details: error.message });
}
});

// Endpoint to update a thought
app.put("/thoughts/:id", async (req, res) => {
const { id } = req.params;
const { message } = req.body;

if (!message || message.length < 5 || message.length > 140) {
return res.status(400).json({ error: "Message must be between 5 and 140 characters" });
}

try {
const updatedThought = await Thought.findByIdAndUpdate(
id,
{ message }, // Update the message only
{ new: true }
);

if (!updatedThought) {
return res.status(404).json({ error: "Thought not found" });
}

res.status(200).json(updatedThought);
} catch (error) {
res.status(500).json({ error: "Failed to update thought", details: error.message });
}
});

// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})
console.log(`Server running on http://localhost:${port}`);
});


68 changes: 68 additions & 0 deletions todo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
- [x] week 18 - seting up with local data,
- [x] video tue 27
- [x] video wend 28 > maybe something is wrong here, idk
- [x] week 19 - [place-things-into-the-database]


- [x] deploy the backend in render
- [x] Your API should use Mongoose models to model your data and use these models to fetch data from the database.
- [x] Your API should validate user input and return appropriate errors if the input is invalid.
- [x] You should implement error handling for all your routes, with proper response statuses.
- [x] video of tue
- [x] i have commented out the back end, data seems to be fetch from the front, fix that! and fix the back end, i feel i'm almost there.
- [x] Ensure the frontend is sending the correct requests to the backend:
- Check the request URLs and payloads.
- Add logs to the frontend functions to debug the requests.
- [x] video of wen jun 4th
- [x] why is there no happy thought been shown?
- [x] check the render deployment if it works
- [x] check MongoDB
- [x] render nad mongo are connected
- [x] test the frontend connection to render with postman
- [x] try to fix error
- [x] look throught all classes again and try to fix problem with my code
- [x] seems not possible to add a thought, edit or remove a thuoght not even to like
- [x] Your frontend should be updated with the possibility to Update and Delete a thought.





- [] week 20
- [x] add a btn for edit,
- [x] add a btn for delete
- [x] use postman to test the endpoint, results:
- [x] ADD THOUGHT POST /thoughts - **!!!FAILD!!!**
"error": "Failed to create thought" - 500 Internal Server Error
- [x] LIKE THOUGHT - error 404 not found **!!!FAILD!!!**
- [x] EDIT A THOUGHT **!!WORKS!!**
- [x] DELETE A THOUGHT **!!WORKS!!**

- [] could the error be related to authentication?

- [x] Editing, cancelling and creatign a new thought when working with the deployed database is not working.


- [] Your API should have routes to register and log in
- [] Your endpoints to Create, Update and Delete should be authenticated
- [] Your frontend should have a registration form which POSTs to the API to create a new user.
- [] Your frontend should have a login form to authenticate the user.
- [] Your passwords in the database should be encrypted with bcrypt.
- [] You should implement error handling. Your API should let the user know if something went wrong. Be as specific as possible to help the user, e.g. by validating the user input when creating a new user, and return "That email address already exists". Include correct status codes. Error messages should also be shown on the frontend.
- [] The validation should ensure unique email addresses and/or usernames, depending on how you'd like to structure your User model.

= = = extras

- [] make the edit text frame look nicer
- [] make the text frame in edit expandable
- [] should i use react router?
- [] clean up components in frontend
- [] move the edit and delte btns





**NOTES**: maybe I have to fix the endpoints? Have to look at week 19 to check what are the mistaked with the diployed data, i think the problem is there.
- **13.06 - 16:08** it is fetching data from the deployed data, but seems i can't add likes, remove or edit anything
- **video of we** got at min 00:34