-
Notifications
You must be signed in to change notification settings - Fork 514
Expres.js and MongoDB-backed Happy Thoughts #506
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
base: master
Are you sure you want to change the base?
Conversation
| validate: [ | ||
| { | ||
| validator: function (value) { | ||
| return value.length >= 5; | ||
| }, | ||
| message: (props) => | ||
| `Message must be at least 5 characters. Your message has ${props.value.length} characters.`, | ||
| }, | ||
| { | ||
| validator: function (value) { | ||
| return value.length <= 140; | ||
| }, | ||
| message: (props) => | ||
| `The maximum length of a message is 140 characters. Your message has ${props.value.length} characters.`, | ||
| }, | ||
| ], |
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.
⭐
| app.put("/thoughts/:id/like", async (req, res) => { | ||
| const { id } = req.params; | ||
| const { action } = req.body; // Expecting "add" or "remove" in the request body | ||
|
|
||
| if (!["add", "remove"].includes(action)) { | ||
| return res | ||
| .status(400) | ||
| .json({ error: "Invalid action. Use 'add' or 'remove'." }); | ||
| } | ||
|
|
||
| try { | ||
| const update = | ||
| action === "add" ? { $inc: { hearts: 1 } } : { $inc: { hearts: -1 } }; | ||
|
|
||
| const updatedThought = await Thought.findByIdAndUpdate( | ||
| id, // Find the thought by its ID | ||
| update, // Increment or decrement the `hearts` field | ||
| { new: true, runValidators: true } // Return the updated document | ||
| ); | ||
|
|
||
| if (!updatedThought) { | ||
| return res.status(404).json({ error: "Thought not found" }); | ||
| } | ||
|
|
||
| res.status(200).json(updatedThought); | ||
| } catch (err) { | ||
| res | ||
| .status(500) | ||
| .json({ error: "Failed to update like", details: err.message }); | ||
| } |
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.
Good idea! ⭐ However, I think it would make sense with a PATCH req instead of PUT (since we're not replacing the whole resource)
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.
Great advice, thank you Matilda! 🙏
Links
View API »
View Frontend Site »