Skip to content

[Dev] Generate short urls in Hasura

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.

I followed this video as a starter tutorial

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()
 LANGUAGE plpgsql
AS $$
  shortid text;
  shortid := encode("SchemaName".gen_random_bytes(6), 'base64');
  shortid := replace(shortid, '/', '_');
  shortid := replace(shortid, '+', '-');
  RETURN shortid;

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.


Leave a Reply

Your email address will not be published.