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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ node_modules
.env.development.local
.env.test.local
.env.production.local
package-lock.json
package-lock.json
.codegpt
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.
This week I created the backend for my Happy Thoughts twitter like app. https://happythoughtsbyanna.netlify.app/
The backend has been created with node and express and the thoughts and likes are stored using MongoDB.

## 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 started out by creating a Mongoose schema to define the structure of the thoughts collection in the database. I defined GET routes for listing all available endpoints and fetching all thoughts, and POST routes for creating new thoughts and liking a specific thought. My biggest challenges was the debugging issues, Identifying why some actions (e.g., liking a thought or fetching data) didn’t work as expected and resolving them step by step.

## 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-42bh.onrender.com
8 changes: 6 additions & 2 deletions 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",
"express": "^4.17.3",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"express-list-endpoints": "^7.1.1",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1"
}
}
}


96 changes: 89 additions & 7 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,106 @@
import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import listEndpoints from "express-list-endpoints";
import dotenv from "dotenv";

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

// Connect to Mongo Atlas using connection string from env. file
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/thoughts";

mongoose
.connect(mongoUrl)
.then(() => {})
.catch((error) => {
console.error("Error connecting to MongoDB:", error.message);
process.exit(1); // Exit if connection fails
});

// Setting a 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);

// 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 port = process.env.PORT || 9000;
const app = express();

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

// Start defining your routes here
app.get("/", (req, res) => {
res.send("Hello Technigo!");
// Start route
app.get("/", (request, response) => {
const endpoints = listEndpoints(app); // Fetch all available routes
response.json({
message:
"Welcome to the Happy Thoughts API! Below are the available endpoints",
endpoints: endpoints, // Send the list of endpoints as JSON
});
});

// Get all thoughts (sorted by most recent)
app.get("/thoughts", async (request, response) => {
try {
const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20);
response.status(200).json(thoughts);
} catch (error) {
response.status(400).json({ error: error.message });
}
});

// Create a new thought
app.post("/thoughts", async (request, response) => {
const { message } = request.body;

try {
const newThought = await Thought.create({ message });
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 👍

response.status(201).json(newThought);
} catch (error) {
response.status(400).json({ error: error.message });
}
});

/// Like a specific thought
app.post("/thoughts/:thoughtId/like", async (request, response) => {
const { thoughtId } = request.params; // Get the thoughtId from the URL params

// const thought = await Thought.findById(thoughtId); // Find the thought by its ID

try {
const updatedThought = await Thought.findByIdAndUpdate(
thoughtId,
{ $inc: { hearts: 1 } }, // Increment the hearts count
{ new: true } // Return the updated document
);

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

response.status(200).json(updatedThought); // Respond with the updated thought
} catch (error) {
console.error("Error updating thought:", error);
response.status(400).json({ error: error.message });
}
});

// Start the server
Expand Down