We have been using Hasura graphql engine as a boostrap “backend” and recently we encountered a design problem: we need to generate a short url link e.g.
https://findnbuy.me/s/w6IwufKj
I followed this video as a starter tutorial https://www.youtube.com/watch?v=DdycuIVb2vI
Actually the solution in the video needs some tweaks when using hasura cloud instead of the offline version
Here is the SQL needed to be run on the db server
CREATE OR REPLACE FUNCTION "SchemaName".gen_unique_short_id()
RETURNS text
LANGUAGE plpgsql
AS $$
DECLARE
shortid text;
BEGIN
shortid := encode("SchemaName".gen_random_bytes(6), 'base64');
shortid := replace(shortid, '/', '_');
shortid := replace(shortid, '+', '-');
RETURN shortid;
END;
$$;
The replace clauses make the output shortid url friendly.
Current version of hasura, as this blog is posted, needs schema specific functions def. So every time to define or call a function we need to add prefix "SchemaName"
Btw gen_random_bytes is a function of pgcrypto, so make sure to have installed. (In my case it is installed by default on heroku).
After defining the function, when creating new columns we can use it as default value for the column.