More efficient way to handle user verification
Unanswered
Orinoco Crocodile posted this in #help-forum
Orinoco CrocodileOP
So I have a .delete endpoint in order to delete products. I have some validation where I am checking that the logged in user is the seller of said product first before they can delete. As you can see in the code below, I am handling the verification and the delete separately. My question is if there is a way to do the seller verification and the delete operation simulataneously so as not to make 2 separate queries to the database.
export async function DELETE(req: Request, { params }: Params) {
await mongooseConnect();
try {
const { id } = params;
const session = await getServerSession(authOptions);
const productById = await Product.findById(id);
if (productById.seller?.toString() !== session?.user?._id) {
return new Response(
JSON.stringify({ errorMessage: "Unauthorized request" }),
{ status: 401 }
);
}
await Product.deleteOne({ _id: id });
return new Response(JSON.stringify(true), { status: 200 });
} catch (error) {
return new Response(JSON.stringify(error), { status: 500 });
}
}6 Replies
Giant panda
Can't you somehow call
deleteOne like deleteOne({ _id: id, seller: session?.user?._id })?But generally speaking there is nothing really bad about performing two queries.
Especially since I assume this won't be called millions of times per minute
Orinoco CrocodileOP
Yeah, you're right. I will just leave it. Because it's clearer and more readable separated out into two queries, even if there is a way to combine the two.
Giant panda
Only optimize if you have actual metrics showing your hot paths aren't performing well.
Until then do what feels easier to understand.