0

im using Hasura with Postgres

Its possible to allow the users to increment a column in a table only by one and not letting them change the whole number ?

For example im afraid that letting the user "update" the "likes"

mutation update_likes {
  update_article(
    where: {id: {_eq: 1}},
    _inc: {likes: 1}
  ) {
    affected_rows
    returning {
      id
      likes
    }
  }
}

im scared that the user will be able to modify the query and update the likes to the number he wants.

Thanks!

P.S the code is an example from the official hasura website: https://hasura.io/blog/updating-data-using-mutations-on-hasura-graphql-87c7e22503bc/

Cristian David
  • 674
  • 5
  • 11
  • Simply do not change the value of the number by a user’s input and instead simply increment the existing value. Looking at your code you need to increment the value outside of graphql in order to do custom handling. As far as different increments by user role then simply get their role and conditionally allow them to “incrementBy” based on their role type. – A Webb May 23 '21 at 18:51
  • In this type of usecases, I think you should consider using hasura actions. – Endriyas May 24 '21 at 08:23

1 Answers1

1

I ended up using postgres functions and trigger to achieve this.

I hope it can be useful for someone trying to do the same thing:

CREATE OR REPLACE FUNCTION inc_entries()
    RETURNS trigger AS $BODY$
    BEGIN
    -- We increment the total entries on giveaway id
    UPDATE giveaways SET total_entries = total_entries + 1 WHERE id = NEW.giveaway;
    -- We increment the entries on current user id
    UPDATE participants SET entries = entries + 1 WHERE id = NEW.user;
    RETURN NEW;
    END;
    $BODY$ LANGUAGE plpgsql;

CREATE TRIGGER inc_entries BEFORE INSERT ON "entries" FOR EACH ROW EXECUTE PROCEDURE inc_entries();
Cristian David
  • 674
  • 5
  • 11