Necessity checking if video exists or not

export const addComment = asyncHandler(async (req, res) => {
const { videoId } = req.params;

if (!isValidObjectId(videoId)) {
throw new ApiError(400, "Invalid video id");
}

const { content } = req.body;

if (!content) {
throw new ApiError(400, "Content is required");
}

const comment = await Comment.create({
content,
owner: req.user?._id,
video: videoId
})

if (!comment) {
throw new ApiError(500, "Comment creation failure");
}

return res.status(200).json(new ApiResponse(200, comment, "Comment created"))
})
export const addComment = asyncHandler(async (req, res) => {
const { videoId } = req.params;

if (!isValidObjectId(videoId)) {
throw new ApiError(400, "Invalid video id");
}

const { content } = req.body;

if (!content) {
throw new ApiError(400, "Content is required");
}

const comment = await Comment.create({
content,
owner: req.user?._id,
video: videoId
})

if (!comment) {
throw new ApiError(500, "Comment creation failure");
}

return res.status(200).json(new ApiResponse(200, comment, "Comment created"))
})
here I am making a add comment to video controller i am fetching the video id (mongoDB id) from url param and user id from req.user (a custom middleware is responsible to check if user is logged in or not and if so adds the user to req object) then if video id is valid mongo id and comment content exists I am creating a new comment doc. Now my question is i am not checking if a video with that ID already exists or not, so Should I do a query for that or do i not have to since user will have to click a video in order to be able to comment on it
6 Replies
Jochem
Jochem7mo ago
you have to weigh the risks and costs and rewards You can just add the comment without, but that runs the risk of someone dumping unaffiliated comments into your database if they figure out how your API works. That may or may not be a problem. The cost to prevent that is slightly more cycles to process a comment, which may or may not be a problem. in an RDBMS, I'd solve this by simply having the videoId column be required and a foreign key pointing to the videos table. Once that becomes an issue, you can rethink your strategy with actual data rather than guessing at what will be more important
glutonium
glutoniumOP7mo ago
hmm.. so there's no direct ans. it's depends on how much risk m willing to take here 1 more query won't be much of an issue what's RDBMS?
Jochem
Jochem7mo ago
databases like MySQL / Postgres. Relational Database Management System
glutonium
glutoniumOP7mo ago
oooh I see i see
Jochem
Jochem7mo ago
basically "not mongo" or "the database style 99% of the internet uses"
glutonium
glutoniumOP7mo ago
Ok I gotchu ig I'll add another query then tnx brother
Want results from more Discord servers?
Add your server