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
38 changes: 33 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,41 @@
# Project Happy Thoughts API

Replace this readme with your own information about your project.
This is a backend API for the Happy Thoughts app, built using Express.js, MongoDB (via Mongoose), and CORS.

Start by briefly describing the assignment in a sentence or two. Keep it short and to the point.
The app allows users to post, retrieve, and like "thoughts" (messages), which are stored in a MongoDB database.

## The problem
## Features
Post Thoughts: Users can submit a message (between 5 to 140 characters) to create a new thought.

Like Thoughts: Users can "like" a thought, which increases the "hearts" count for that particular thought.

Get Thoughts: Users can retrieve the latest 20 thoughts, sorted in descending order by creation date.

CORS Support: The API allows cross-origin requests from a specific frontend hosted on Netlify (https://post-happy-thoughts.netlify.app).

## Technologies Used
Node.js: Backend runtime environment.

Express.js: Web framework for building the API.

MongoDB: NoSQL database used to store thoughts and related data.

Mongoose: MongoDB object modeling tool.

dotenv: For managing environment variables.

CORS: Cross-origin resource sharing to allow specific domains to interact with the API.

## API Endpoints

GET /thoughts: Retrieves the 20 most recent thoughts.

POST /thoughts: Submits a new thought with a message.

POST /thoughts/:id/like: Likes a thought by incrementing the hearts count.

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?

## View it live
project-happy-thoughts-api-production-5d1d.up.railway.app


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.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
"@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",
"mongoose": "^8.0.0",
"nodemon": "^3.0.1"
}
}
}
99 changes: 92 additions & 7 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,112 @@
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;
dotenv.config()

const mongoURI = process.env.MONGODB_URI

mongoose.connect(mongoURI)
.then(() => {
console.log('MongoDB successfully connected!')
})
.catch((error) => {
console.error('Error to connect with MongoDB', error)
})

// Setting a Schema and model
const Thought = mongoose.model("Thought", new mongoose.Schema({
message: {
type: String,
required: true,
minlength: 5,
maxlength: 140
},
hearts: {
type: Number,
default: 0
},
likedBy: [{
type: mongoose.Schema.Types.ObjectId, //stores preferences to user object
ref:"User"
}],
createdAt: {
type: Date,
default: () => new Date()
}
}))
// 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(cors({
origin: "https://post-happy-thoughts.netlify.app",
methods: ["GET", "POST"], // Specify allowed methods
allowedHeaders: ["*"], // Specify allowed headers, in this case all
}));

app.use(express.json());

// Start defining your routes here
app.get("/", (req, res) => {
res.send("Hello Technigo!");
const endpoints = listEndpoints(app);
res.json({
message: "These are the endpoints of the Happy Thoughts API",
endpoints: endpoints
})
});

app.get("/thoughts", async (req, res) => {
try {
// returning 20 thoughts in descending order
const thoughts = await Thought.find().sort({createdAt: "desc"}).limit(20).exec();
res.json(thoughts)
}catch (error) {
console.error('Error retrieving thoughts', error);
res.status(500).send('Server error');
}
});

app.post("/thoughts", async (req, res) => {
try{
//retrieve the information sent by the client to the API endpoint
const {message} = req.body;
//use the mongoose model to create the DB entry
const newThought = new Thought({message});
await newThought.save();

res.status(201).json(newThought);
} catch(error) {
res.status(400).json({message: "Could not save thought", errors: error.err.errors})
}
});

// Like a thought
app.post("/thoughts/:id/like", async (req, res) => {
try {
const {id} = req.params
const thought = await Thought.findById(id)
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.

Why not use findByIdAndUpdate for updating hearts directly instead of fetching, modifying, and saving? 🤔

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thank you :) I changed it

if(!thought) {
return res.status(404).json({message: "Thought was not found"})
}

// Update hearts count
const newHearts = thought.hearts % 2 === 0 ? thought.hearts +1 : thought.hearts -1;

const updatedThought = await Thought.findByIdAndUpdate(id, {hearts: newHearts}, {new: true});

res.status(200).json(updatedThought);
} catch (error){
console.error("There is an errow by liking the thought", error);
res.status(500).json({message: "Could not like thought"})
}
})

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