Hasura Actions using Netlify Functions

Hasura is an Instant GraphQL API generating engine, where all the base APIs are generated in microseconds when a DB is connected. Also, they provide support for integrating the business logics as well using “Hasura Actions”.

Netlify functions are AWS’s serverless lambda functions that allow you to define your business logic and functions as an API and expose them with an endpoint.

Now we are going to implement business logic using netlify functions in Hasura using “actions” in these simple steps.

We can also use Hasura’s Actions to add REST endpoints to Hasura’s GraphQL schema.

Step-1: Create a Function in an app

npm install -g netlify-cli

Once, the netlify-cli installed, go to the project’s root folder, and link your netlify site to the folder.

netlify link

Once linked, type the following command to create a function

netlify functions:create

There will be a list of predefined templates shown while netlify functions:create is triggered. Please choose the hello-world template.

Now, a function will be created in netlify/functions/hello-world/hello-world.js

Step-2: Define the functions with logics

The most important thing to remember is to add the code and message to the response body. These are displayed in Hasura’s GraphQL errors (whenever the API is returning an error in Hasura, they follow the GraphQL error standard).

The error in Hasura is displayed like this:

Error state in Hasura GraphQL

So, to display the message and code for the error, they both should be present in the response body in case of an error.

Step-3: Add the function to Hasura using Actions

  1. Login to your Hasura console and go to the “Actions” tab
  2. Click on the “Create” button
  3. Define your inputs and outputs of your API as shown below. (Learn more about the inputs & outputs on Hasura)
  4. Add the endpoint of your API under the Handler.
Creating an Action

We can also, modify the permission of the actions if we are using a role-based permission mechanism.

Step-4: Try out the actions using Hasura GraphQL

Success state of an Action

The error state from the netlify function is displayed like this.

  • When the email is not sent along with the request the following error is shown.
“Input not given/undefined” error
  • When the user is not found with the requested email, the following error is shown.
“User is not found” error

Horray! We have implemented a custom business logic using netlify in the Hasura GraphQL engine.

To know more about Hasura's actions, visit their website here.

Say Hi, It’s free at @matheswaaran_S or https://matheswaaran.com

Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store