Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Happy Thoughts API - Mai #478

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
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
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# 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.
In this project, I developed a backend API for "Happy Thoughts", a social media platform centered on sharing positive and encouraging messages. The goal was to replicate the functionality of an existing API used in a React frontend, allowing users to post thoughts, view a list of recent thoughts, and 'like' their favorites.

## 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?
I used Node.js, Express, and MongoDB to create the API. I planned the project by first designing the data model and then implementing the routes needed for the frontend. If I had more time, I would add features like thought categorization and user authentication.

## 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.
Backend: https://project-happy-thoughts-api-vya8.onrender.com
Frontend: https://project-happy-thoughts-maikanetaka.netlify.app/
20 changes: 20 additions & 0 deletions models/thought.js
Copy link
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 this out 👍

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import mongoose from "mongoose";

export const ThoughtSchema = new mongoose.Schema({
message: {
type: String,
required: true,
minlength: 5,
maxlength: 140,
},
hearts: {
type: Number,
default: 0,
},
createdAt: {
type: Date,
default: Date.now,
},
});

export const Thought = mongoose.model("Thought", ThoughtSchema);
Copy link
Contributor

Choose a reason for hiding this comment

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

Best practice to always leave an empty line in the end of every JS file

9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "project-happy-thoughts-api",
"version": "1.0.0",
"description": "Starter project to get up and running with express quickly",
"type": "module",
"scripts": {
"start": "babel-node server.js",
"dev": "nodemon server.js --exec babel-node"
Expand All @@ -12,9 +13,11 @@
"@babel/core": "^7.17.9",
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.17.3",
"mongoose": "^8.0.0",
"express": "^4.19.2",
"express-list-endpoints": "^7.1.0",
"mongoose": "^8.3.5",
"nodemon": "^3.0.1"
}
}
}
96 changes: 87 additions & 9 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,105 @@
import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import expressListEndpoints from "express-list-endpoints";
import { Thought } from "./models/thought.js";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
const mongoUrl =
process.env.MONGO_URL || "mongodb://localhost:27017/happy-thoughts";

mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
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
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
const routes = [
{
path: "/thoughts",
method: "get",
description: "Get the last 20 thoughts in descending order",
handler: async (req, res) => {
try {
const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20);
res.json(thoughts);
Copy link
Contributor

Choose a reason for hiding this comment

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

Would be nice with a status code here

} catch (error) {
console.error("Error fetching thoughts", error);
res.status(500).json({ message: "Server error" });
}
},
},
{
path: "/thoughts",
method: "post",
description: "Post a new thought with a message",
handler: async (req, res) => {
const { message } = req.body;
if (message.length < 5 || message.length > 140) {
return res
.status(400)
.json({
message: "Please type between between 5 and 140 characters",
});
}
try {
const newThought = new Thought({ message });
await newThought.save();
res.status(201).json(newThought);
} catch (error) {
console.error("Error posting thought:", error);
res.status(500).json({ message: "Server error" });
}
},
},
{
path: "/thoughts/:thoughtId/like",
method: "post",
description: "Like a thought by providing the thought ID",
handler: async (req, res) => {
const { thoughtId } = req.params;
try {
const likedThought = await Thought.findByIdAndUpdate(
thoughtId,
{ $inc: { hearts: 1 } },
{ new: true }
);
Comment on lines +64 to +68
Copy link
Contributor

Choose a reason for hiding this comment

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

if (likedThought) {
res.status(200).json(likedThought);
} else {
res.status(404).json({ message: "Thought not found " });
Copy link
Contributor

Choose a reason for hiding this comment

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

👍

}
} catch (error) {
console.error("Error liking thought:", error);
res.status(500).json({ message: "Server error" });
}
},
},
];

routes.forEach((route) => {
app[route.method](route.path, route.handler);
});


app.get("/", (req, res) => {
res.send("Hello Technigo!");
try {
const endpoints = expressListEndpoints(app).map((endpoint) => {
const matchedRoute = routes.find((route) => route.path === endpoint.path);
if (matchedRoute) {
endpoint.description = matchedRoute.description;
}
return endpoint;
});
res.status(200).json(endpoints);
} catch (error) {
console.error("Error generating API documentation:", error);
res.status(500).json({ message: "Server error" });
}
});

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