Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -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/
21 changes: 21 additions & 0 deletions models/Thought.js
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice that you broke out the model 👍 Can be nice for the final project as well, when your project will be bigger

Original file line number Diff line number Diff line change
@@ -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);
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
92 changes: 86 additions & 6 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,104 @@
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();

// Add middlewares to enable cors and json body parsing
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",
});
}
Comment on lines +55 to +69
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice structure 😉

});

// 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
);
Comment on lines +78 to +82
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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


// 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
Expand Down