Skip to content

Instantly share code, notes, and snippets.

@WoolDoughnut310
Created October 28, 2022 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WoolDoughnut310/04d4aef81608e460a40b0b231b4d3f1c to your computer and use it in GitHub Desktop.
Save WoolDoughnut310/04d4aef81608e460a40b0b231b4d3f1c to your computer and use it in GitHub Desktop.
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