diff --git a/README.md b/README.md index 6a75d8e1..65992c02 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,19 @@ # Project Happy Thoughts API -Replace this readme with your own information about your project. - -Start by briefly describing the assignment in a sentence or two. Keep it short and to the point. +The Happy Thoughts API is designed to integrate with the previously created Happy Thoughts frontend that allows users to post a thought, view recent posts, and like others' thoughts. ## The problem -Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next? +First I analyzed the requirements to define routes (GET /thoughts, POST /thoughts, PATCH /thoughts/:thoughtId/like) and structured the project so there was a clear separation between the Thought model and routes. + +Technologies I used included Node.js and Express.js for server-side development, Mongoose for database modeling and interaction with MongoDB, MongoDB Atlas for cloud-based database storage, Postman for testing endpoints locally, and Render for deployment. + +I created a Thought model with validation for message, hearts, and createdAt. I then implemented the routes to GET- fetch the 20 most recent thoughts, POST- validate input and create new thoughts, and PATCH- increment hearts count for a specific thought. + +If I had more time, I would try stretch goals like adding categories to different types of thoughts or allowing users to remain anonymous or add their names by updating the Thought model. I would also add pagination for improved scalability. ## View it live -Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about. +https://project-happy-thoughts-api-ph1w.onrender.com/ + +https://happy-thoughts-joyce.netlify.app/ diff --git a/models/Thought.js b/models/Thought.js new file mode 100644 index 00000000..dec7030d --- /dev/null +++ b/models/Thought.js @@ -0,0 +1,21 @@ +import mongoose, { Schema } from "mongoose"; + +const ThoughtSchema = new mongoose.Schema({ + message: { + type: String, + required: true, + minlength: 5, + maxlength: 140, + }, + hearts: { + type: Number, + default: 0, + }, + createdAt: { + type: Date, + required: true, + default: () => new Date(), + }, +}); + +export const Thought = mongoose.model("Thought", ThoughtSchema); diff --git a/package.json b/package.json index 1c371b45..9e6c050a 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", + "envdot": "^0.0.3", "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..eb0e1066 100644 --- a/server.js +++ b/server.js @@ -1,14 +1,17 @@ import cors from "cors"; import express from "express"; import mongoose from "mongoose"; +import dotenv from "dotenv"; +import { Thought } from "./models/Thought"; -const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo"; +dotenv.config(); + +const mongoUrl = + process.env.MONGO_URL || "mongodb://localhost/project-happy-thoughts"; mongoose.connect(mongoUrl); mongoose.Promise = Promise; -// Defines the port the app will run on. Defaults to 8080, but can be overridden -// when starting the server. Example command to overwrite PORT env variable value: -// PORT=9000 npm start +// Defines the port the app will run on. const port = process.env.PORT || 8080; const app = express(); @@ -16,9 +19,86 @@ const app = express(); app.use(cors()); app.use(express.json()); -// Start defining your routes here +// Define the root endpoint app.get("/", (req, res) => { - res.send("Hello Technigo!"); + res.json({ + message: "Welcome to Joyce's Happy Thoughts API!", + endpoints: { + getThoughts: "GET /thoughts", + postThought: "POST /thoughts", + likeThought: "PATCH /thoughts/:thoughtId/like", + }, + }); +}); + +// Fetch the 20 most recent thoughts, sorted by createdAt in descending order +app.get("/thoughts", async (req, res) => { + try { + const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20); + res.json(thoughts); + } catch (error) { + res.status(500).json({ error: "Error fetching thoughts" }); + } +}); + +// Post a new thought +app.post("/thoughts", async (req, res) => { + const { message } = req.body; + + try { + // Validation of message before saving + if (!message || message.length < 5 || message.length > 140) { + throw new Error("Message must be between 5 and 140 characters"); + } + + // Create and save a new thought + const newThought = await new Thought({ message }).save(); + + // Send success response with saved thought + res.status(201).json({ + success: true, + response: newThought, + message: "Thought was successfully created!", + }); + } catch (error) { + res.status(400).json({ + success: false, + response: error.message, + message: "Failed to create thought", + }); + } +}); + +// Increment the hearts count of a specific thought +app.patch("/thoughts/:thoughtId/like", async (req, res) => { + const { thoughtId } = req.params; + + try { + // Find the thought by ID and increment its hearts + const updatedThought = await Thought.findByIdAndUpdate( + thoughtId, + { $inc: { hearts: 1 } }, // Increment the hearts field by 1 + { new: true } // Return the update + ); + + // If no thought is found, throw an error + if (!updatedThought) { + throw new Error("Thought not found"); + } + + // Send a success response with the updated thought + res.status(200).json({ + success: true, + response: updatedThought, + message: "Successfully liked the thought!", + }); + } catch (error) { + res.status(400).json({ + success: false, + response: error.message, + message: "Failed to like thought", + }); + } }); // Start the server