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 Project - Elina Eriksson Hult #505

Open
wants to merge 8 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
11 changes: 3 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
# 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.
This project is a Happy Thoughts Messaging API built with Express and MongoDB. It lets users create new thoughts, view the latest ones, and like a thought by adding hearts. I connected the project with my frontend Happy Thoughts project, enabling the API to handle requests and interact with the frontend.

## 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?
This project uses Express for the backend API, MongoDB with Mongoose for data storage, and dotenv for environment variable management. CORS handles cross-origin requests, and list-endpoints-express lists available API routes. I started with connecting the project to MongoDB Atlas and then built the required endpoints step by step. I made a small mistake when importing the express-list-endpoints, which caused my endpoints to appear incorrectly. After realizing the mistake, I was able to fix it and get the home route to display the endpoints in a structured order.

## 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-pxns.onrender.com/
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"dotenv": "^16.4.7",
"express": "^4.17.3",
"express-list-endpoints": "^7.1.1",
"list-endpoints-express": "^1.0.1",
"mongodb": "^6.12.0",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1"
}
}
}
107 changes: 99 additions & 8 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,115 @@
import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";
import listEndpoints from "express-list-endpoints";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl);
mongoose.Promise = Promise;
// Load environment variables from env. file
dotenv.config();

// 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
// Mongoose schema and model
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
}
});

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

// MongoDB connection setup
const mongoUrl = process.env.MONGO_URI;

mongoose.connect(mongoUrl)
.then(() => {
console.log('Connected to MongoDB Atlas');
})
.catch((error) => {
console.error('Error connecting to MongoDB Atlas:', error);
});

// Defines the port the app will run on, defaults to 8080
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
// Route definitions
// Home route showing all endpoints
app.get("/", (req, res) => {
res.send("Hello Technigo!");
const endpoints = listEndpoints(app); // Automatically list all endpoints
res.json({
message: "Hello and welcome to the Happy Thoughts API! Here are all the available endpoints:",
endpoints: endpoints
});
});

// Fetch all thoughts and show the latest 20 thoughts
app.get("/thoughts", async (req, res) => {
try {
const thoughts = await Thought.find()
.sort({ createdAt: -1 }) // Sort in descending order
.limit(20); // Limit to 20 results

res.status(200).json(thoughts); // Return thoughts
} catch (error) {
res.status(400).json({ error: error.message }); // Handle error
}
});

// Create a new thought and save thought including id
app.post("/thoughts", async (req, res) => {
try {
const { message } = req.body

if (!message || typeof message !== "string") {
return res.status(400).json({ error: "Invalid input. 'message' is required and must be a string" }); // Handle error
}

const thought = new Thought ({ message });
const savedThought = await thought.save();

console.log("New thought saved:", savedThought);
res.status(201).json(savedThought);
} catch (error) {
console.error("Error saving thought:", error);
res.status(500).json({ error: "An error occurred while saving the thought"}); // Handle error
}
});

// Like a thought and save the like
app.post("/thoughts/:thoughtId/like", async (req, res) => {
try {
const { thoughtId } = req.params;

const thought = await Thought.findByIdAndUpdate(
thoughtId,
{ $inc: { hearts: 1} },
{ new: true }
);

if (!thought) {
return res.status(404).json({ error: "Thought not found." }); // No thought was found with this ID
}

// Respond with the updated thought
res.status(200).json(thought);
} catch (error) {
console.error("Error updating hearts:", error.message);
res.status(500).json({ error: "An error occurred while liking the thought." })
}
});

// Start the server
Expand Down