I'm working on a project where users need to like a particular content among other things. The project is running on an aws ec2 instance and uses a rds postgres instance.
There is a separate table with a column of type integer[] for storing the id of all the users that liked a particular content. Before adding a user to the array, I should check that 1-the content with the given id exists and 2-the user has not already liked the content.
There are two methods to do this. Retrieving the content by id and returning 404 if it does not exist. Otherwise retrieve the row related to that content and check if the id of the user related to the current request already exists in the array and returning 400 if it does. Otherwise add the id of the user to the array.
But this means that for this particular request, I'm executing three queries to the database which involves three network calls from the ec2 instance to the rds instance.
The second method solves this problem. You just have to do all that checking in the rds instance, so this is what I wrote:
create function like(client integer, content integer) returns integer as $$ begin
if(exists(select * from contents where id=content)) then
if(select client=any(likes) from "contentInteractions" where "contentId"=content) then
return 409;
else
if(not exists(select * from "contentInteraction" where "contentId"=content)) then
insert into "contentInteraction" ("contentId", likes) values (content, '{}');
end if;
update "contentInteraction" set likes = likes || client where "contentId"=content;
return 200;
end if;
else
return 404;
end if;
end; $$ language plpgsql;
So, my question is, am I over-complicating things for no reason? Is it worth the reduced code clarity(because anyone who reads the code should refer to the definition of this function in the migrations)?
Thanks