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

Arnau's Happy thoughts API #488

Open
wants to merge 27 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
663a985
add npm dependencies: mongoDB och express.list-endpoints
May 18, 2024
a7e5e61
add mongoose moddleware handling
May 18, 2024
76a6ca5
add Thought model
May 18, 2024
32d9048
save middleare and schema to a separate js file
May 18, 2024
cfe75a3
app.post '/thougts' create and test in postman, pause
May 18, 2024
73f010d
seems that every in the API is working, save and deploy
May 18, 2024
4783c0d
deploy to render and changed README
May 18, 2024
bde6de3
deploy failed to render, changed schema file
May 18, 2024
5677b05
deploy failed to render, add changes in mongoose.connect
May 18, 2024
e8612ae
add changes to the code, kill schema.js and mideware.js KISS metodology
May 18, 2024
c3a3aaf
add changes to the code, remove MONGO DRIVER from line 8
May 18, 2024
a6b2b66
remove pull template
May 18, 2024
0853e7f
add devDependencies in package.jonson, for bavel/core and preset-env
May 18, 2024
53bfe1f
run npm install after making last changes on package.json
May 18, 2024
ab21dc5
this will not save the deploy problem but now the app.post/thougths i…
May 18, 2024
2fa0a41
add .env file open Atlas account and create Arnau-cluster, create sec…
May 18, 2024
26d4e0c
correct MONGO_URL on .env
May 19, 2024
4fc2ad2
add forntend file on README
May 19, 2024
ab4a57f
push changes and try again
May 19, 2024
c67cdae
STUCK, server not connecting to MongoDB compass
May 19, 2024
528f750
exiting, after hours without thoughts collection in compass now final…
May 19, 2024
6d43036
change render url
May 19, 2024
49ffa89
create a new cluster in atlas and add a new .env url string
May 19, 2024
4dccb98
uppdate connection code enl GPT
May 19, 2024
694892e
uppdate MONGO_URL variable
May 20, 2024
328e28e
uppdated password on MONGO_URL and collection name in url
May 20, 2024
a27b300
removed some extra code on mongoose.connect
May 20, 2024
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.
This week's project was about creating the backend for the Happy Thoughts project we did earlier in the bootcamp. This time, I had to code the server of the API where data from the MongoDB database can be handled using GET and POST methods.

## 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?
The main challenge was understanding and implementing the necessary code to connect to a database within a short timeframe. I got stuck while trying to connect to server to MongoDB compass no matter what it wasn't connecting.

## 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: [here](https://project-happy-thoughts-api-w8r4.onrender.com)
Frontend: [here](https://my-happy-thoughts-project.netlify.app/)
13 changes: 9 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.17.9",
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.17.3",
"mongoose": "^8.0.0",
"express-list-endpoints": "^7.1.0",
"mongodb": "^6.6.2",
"mongoose": "^8.4.0",
"nodemon": "^3.0.1"
},
"devDependencies": {
"@babel/core": "^7.17.9",
"@babel/preset-env": "^7.16.11"
}
}
}
7 changes: 0 additions & 7 deletions pull_request_template.md

This file was deleted.

95 changes: 89 additions & 6 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,107 @@
import cors from "cors";
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import expressListEndpoints from "express-list-endpoints";

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

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/happyThoughts";
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
// PORT=8080 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());
app.use((req, res, next) => {
if (mongoose.connection.readyState === 1) {
next();
} else {
res.status(503).json({ error: "Service unavailable." });
}
});
Comment on lines +21 to +27
Copy link
Contributor

Choose a reason for hiding this comment

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

👍


//Models
const Thought = mongoose.model("Thought", {
message: {
type: String,
required: true,
minlength: 5,
maxlength: 140,
},
hearts: {
type: Number,
default: 0,
},
createdAt: {
type: Date,
default: () => new Date(),
},
});

// Start defining your routes here
//Here the routes GET and POST
app.get("/", (req, res) => {
res.send("Hello Technigo!");
const endpoints = expressListEndpoints(app);
const documentation = {
Welcome: "This is the Happy Thoughts API!",
Endpoints: {
"/": "Get API documentation",
"/thoughts": "Get 20 latest thoughts",
"/thoughts/:thoughtId/like": "Like a specific thought",
},
};
res.json(documentation);
});

app.get("/thoughts", async (req, res) => {
try {
const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20);
res.status(200).json(thoughts);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
Comment on lines +61 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.

Nice and clean endpoint 👍


app.post("/thoughts", async (req, res) => {
try {
const thought = new Thought({ message: req.body.message });
await thought.save();
res.status(201).json({
success: true,
response: thought,
message: "Thought posted",
});
} catch (error) {
res.status(400).json({
success: false,
response: error,
message: "Could not save thought.",
});
}
});

app.post("/thoughts/:thoughtId/like", async (req, res) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Haha I love the idea with 1, 10, 100 likes, but consider dealing with that from the backend side so you don't need to call your API 100 times 🙈

Copy link
Author

Choose a reason for hiding this comment

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

hehe you are right, it has to be done in the backend.

try {
const { thoughtId } = req.params;
const thought = await Thought.findByIdAndUpdate(
thoughtId,
{ $inc: { hearts: 1 } },
{ new: true }
);
Comment on lines +91 to +95
Copy link
Contributor

Choose a reason for hiding this comment

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


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

res.status(200).json(thought);
} catch (error) {
res.status(400).json({ error: error.message });
}
});

// Start the server
Expand Down