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

Erika's Happy Thoughts API #483

Open
wants to merge 5 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
12 changes: 7 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# 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 is an API that works with the Happy Thoughts Project on https://boisterous-brioche-b12b23.netlify.app/. It uses MongoDB to store posted thoughts and likes. A get-request will have a response with the 20 latest thoughts.

## 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?
Working with this project was pretty straight forward with the help of class material, live sessions and previous knowledge. However when I connected it to the frontend project the thought list didn't update as expected when posting a new thought, which was frustrating. Then I did the last touches on my error handling and realised that the response was coming back in a different way from the original project. So I had to change one more line of code in the frontend to update the list with the correct part of the response. And that did the trick!

BTW it was fun to work with post-requests. Now I finally understand why Postman is such a good tool 🙂

I also did my own stretch-goal and added a dislike-path. It works well with my frontend that likes the thought the first time you click the heart, then takes it back the second time you click, then likes it again, then takes it back and so forth.

## 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://tejpex-happy-thoughts-api.onrender.com/
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"express": "^4.17.3",
"mongoose": "^6.12.0",
"express-list-endpoints": "^7.1.0",
"mongodb": "^6.6.2",
"mongoose": "^8.3.5",
"nodemon": "^3.0.1"
}
}
7 changes: 0 additions & 7 deletions pull_request_template.md

This file was deleted.

130 changes: 112 additions & 18 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,121 @@
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import express from "express"
import cors from "cors"
import mongoose from "mongoose"
import expressListEndpoints from "express-list-endpoints"

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
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();
// Defines the port the app will run on and connects to mongoose
const port = process.env.PORT || 8080
const app = express()
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/happy-thoughts"
mongoose.connect(mongoUrl)
mongoose.Promise = Promise

// Add middlewares to enable cors and json body parsing
app.use(cors());
app.use(express.json());
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 +16 to +22
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
app.get("/", (req, res) => {
res.send("Hello Technigo!");
});
const documentation = {
Welcome: "Welcome to the Happy Thoughts API!",
Endpoints: expressListEndpoints(app).map((endpoint) => {
return {
path: endpoint.path,
methods: endpoint.methods,
middlewares: endpoint.middlewares,
}
})
}
res.json(documentation);
})

app.get("/thoughts", async (req, res) => {
try {
const thoughts = await Thought.find().sort({ createdAt: -1 }).limit(20).exec()
if (thoughts.length > 0) {
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.

A status code would be nice here

} else {
res.status(404).json({ error: "No thoughts found." })
}
} catch (err) {
res.status(400).json({ message: "Something went wrong.", error: err.errors })
}
})

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.patch("/thoughts/:id/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.

Nice with patch 🪡

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

Choose a reason for hiding this comment

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

res.status(200).json(thought)
} catch (error) {
res.status(400).json({
success: false,
response: error,
message: "Could not like thought."})
}
})

app.patch("/thoughts/:id/dislike", async (req, res) => {
try {
const thought = await Thought.findByIdAndUpdate(
req.params.id,
{ $inc: { hearts: -1 } },
{ new: true, runValidators: true }
)
res.status(200).json(thought)
} catch (error) {
res.status(400).json({
success: false,
response: error,
message: "Could not dislike thought.",
})
}
})
Comment on lines +101 to +116
Copy link
Contributor

Choose a reason for hiding this comment

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

Haha, love this! ⭐ ⭐ ⭐


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