Awesome
fastify-hasura
A Fastify plugin to have fun with Hasura.
Features
- Fastify decorator over graphql-request to easily request Hasura graphql endpoint.
- Provide routes for Hasura events, actions and cron jobs.
- Secure requests coming from Hasura.
- Easily register handler for Hasura events, actions and cron jobs.
Install
- Install fastify-hasura with:
yarn add fastify-hasura # or npm i --save fastify-hasura
- Register the plugin:
fastify.register(require('fastify-hasura'), {
endpoint: 'yourHasuraGraphqlEndpoint',
admin_secret: 'yourAdminSecret'
})
Usage
Example request on Hasura Graphql Endpoint
const userId = 'yourUserUUID'
const fetchUser = `#graphql
query fetchUser($id: uuid!) {
user: user_by_pk(id: $id) {
password
}
}
`
const { user } = await fastify.hasura.graphql(fetchUser, {
id: userId
})
Example registering event and action:
// Register new_user hasura event
fastify.hasura.registerEvent('new_user', (request, reply) => {
const user = request.event.getNewData()
console.log(user)
})
// Register login hasura action
fastify.hasura.registerAction('login', async (request, reply) => {
const data = request.action.getData('id', 'type', 'user')
console.log(data)
const response = await yourAsyncCustomBusinessLogic(data)
reply.send(response)
})
Note: Requests for events and actions are decorated with hasura-parser. So, you can easily retrieve data in routes with request.event
and request.action
.
Options
endpoint
[ required ]: Your Hasura Graphql Endpoint.admin_secret
[ required ]: Your Hasura admin secret.api_secret
[ optional ]: Highly recommended. Provide an api secret if you want to secure requests from your Hasura instance to your Fastify app. You must configurex-hasura-from-env
headers of all Hasura events, actions and cron jobs with this api secret.routes_prefix
[ optional ]: By default, this plugin build root routes for/events
,/actions
and/crons
. Use this option if you want to prefix this routes. Eg:/hasura
will build routes/hasura/events
and so on...
All options:
fastify.register(require('fastify-hasura'), {
endpoint: 'yourHasuraGraphqlEndpoint',
admin_secret: 'yourAdminSecret',
api_secret: 'yourApiSecret',
routes_prefix: '/hasura'
})
More documentation
Contributions
If you would like to make any contribution you are welcome to do so.
License
Licensed under MIT