Created
October 28, 2022 15:52
-
-
Save WoolDoughnut310/04d4aef81608e460a40b0b231b4d3f1c to your computer and use it in GitHub Desktop.
This file contains 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
router.post( | |
"/:id/favourite", | |
asyncHandler(async (req: Request, res: Response) => { | |
const db = getDb(); | |
const collection = db.collection<Song>("song"); | |
const songId = new ObjectId(req.params.id); | |
const song = await collection.findOne({ | |
_id: new ObjectId(req.params.id), | |
}); | |
// Check if the song exists | |
if (song === null) { | |
res.status(404).send("Song not found"); | |
return; | |
} | |
const favourites = req.user.favourites ?? []; | |
// Define the operator on the favourites list | |
const operator = favourites.find((id) => id.equals(songId)) | |
? "$pull" | |
: "$push"; | |
await db.collection<User>("user").updateOne( | |
{ | |
_id: req.auth.id, | |
}, | |
{ | |
[operator]: { favourites: songId }, | |
} | |
); | |
// Update the user variable in the request | |
req.user = await db | |
.collection<User>("user") | |
.findOne({ _id: req.auth.id }); | |
res.status(200).json(req.user.favourites); | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment