Setup Postgres functions and triggers to perform backend operations like validation and inserting/updating other related data, whenever some inserts/updates happens on tables. Now when you use GraphQL mutations, Postgres triggers run, performing the required backend operations.
Introduction
There are cases where you would want run some custom backend function after an insert happens.
Some examples of this are:
Perform some validation on the server-side. For e.g. in a banking application, validate that deposits cannot be than 0 or lesser.
Insert some related data in a single transaction. For e.g. in a note taking application, create a revision whenever a note is updated.
What is a Postgres trigger ?
A trigger is associated with a table or view and is fired whenever an event occur. The ‘events’ are INSERT, DELETE, UPDATE or TRUNCATE.
Trigger will eventually call a function which will automatically be invoked when a specific event occurs.
Triggers can be invoked in the following scenarios:
Before the operation.
After the operation.
Instead of the operation.
Validation on the server-side
Consider the following data model for a banking-like application:
So to demonstrate the first scenario, we will perform basic validation before an insert into deposit_activity happens. We want to ensure that insert doesn’t happen, if the deposit_amount is ≤ 0 or if the account is inactive.
Let’s create a trigger. You can copy-paste this in the “SQL” tab of Hasura console:
Now to to make deposits into an account, we can just use this insert mutation, and the trigger will make sure that the amount is valid (≥0) and the account is not an inactive account.