-
Notifications
You must be signed in to change notification settings - Fork 511
happy-thoughts-api #500
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
Open
gittebe
wants to merge
26
commits into
Technigo:master
Choose a base branch
from
gittebe:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
happy-thoughts-api #500
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
d1fc583
- defined mongoose schema and model and first endpoints with get and …
dd7810c
- fixed mongoose model and added an endpoint to update the hearts
f18a48e
- added corse middleware to accept requests from netlify
21fe4e2
= I needed to set the origin property in the cors configuration
768c321
- commented cors out
5cf5f56
-added CORS configuration
fde9c3f
= trying to fix cors
709d87c
- still trying to fix cors problems
f231b09
= changed mongoose model
8f1725a
-cors
01cea83
=cors
76dabbd
- cors
b004854
- cors
5b1cd8d
- cors
be4b15f
-cors
329e729
- cleaned code
9d55022
- cors
44b9843
-cors
77aef36
-changed api
0a9cf7d
- fixed api
12bdfa2
- added readme file
d45bb49
- added list of endpoints
4c901fd
- changed the like function so that it can both add or substract hearts
79bddff
- cleaned code
ae9de1b
- changed method to update hearts
515fe06
- fixed typo and defined updatedThought object
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| 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}`); | ||
| }); | ||
| }); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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? 🤔
There was a problem hiding this comment.
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