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
To create a function in the app, you need the
npm install -g netlify-cli
netlify-cli installed, go to the project’s root folder, and link your netlify site to the folder.
Once linked, type the following command to create a function
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
Step-2: Define the functions with logics
Here is an example of a netlify function for Hasura's actions, which check if an email is present in the DB without exposing all the users to the client.
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:
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
Now, we have completed the business logic and created an API using Netlify functions. We have to add this API to Hasura using Actions.
- Login to your Hasura console and go to the “Actions” tab
- Click on the “Create” button
- Define your inputs and outputs of your API as shown below. (Learn more about the inputs & outputs on Hasura)
- Add the endpoint of your API under the Handler.
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
The success state from the netlify functions
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.
- When the user is not found with the requested email, the following error is shown.
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.