Back to Graphql Engine

Quickstart Subscriptions

docs/docs/subscriptions/quickstart.mdx

2.50.02.7 KB
Original Source

import Thumbnail from '@site/src/components/Thumbnail'; import GraphiQLIDE from '@site/src/components/GraphiQLIDE'; import SampleAppBlock from '@site/src/components/SampleAppBlock';

Quickstart Subscriptions

This quickstart will help you create your first subscription. We're going to subscribe to live updates for a notification thread.

<SampleAppBlock dependent />

Step 1: Create a Subscription

Head to the API tab of the Hasura Console and paste in this value:

graphql
subscription UserNotificationSubscription($user_id: uuid = "9bd9d300-65b7-11ed-b908-571fef22d2ba") {
  notifications(where: { user_id: { _eq: $user_id } }) {
    id
    created_at
    message
  }
}

Once hitting run, you should see the following output:

<Thumbnail src="/img/subscriptions/subscriptions-empty_quickstart-cloud2.20.0.png" alt="Hasura Scheduled Trigger architecture" width="1000" />

:::tip That's it?

Yep! Remember, you get subscriptions out of the box with Hasura 🔥 You'll see a few notifications in your results because they're already in the database. To test it — and see new notifications mimicking a client application — let's ping the server with curl in the next step.

:::

Step 2: Insert a notification

To avoid the need for a client application, we'll use curl to insert a notification into the database. You can enter the curl command below into a terminal window, and replace the <YOUR_ADMIN_SECRET> and <YOUR_HASURA_PROJECT_ENDPOINT> values with your own:

shell
curl -X POST -H "Content-Type: application/json" -H "x-hasura-admin-secret: <YOUR_ADMIN_SECRET>" -d '{"query":"mutation InsertNewNotification {\n  insert_notifications_one(object: {user_id: \"9bd9d300-65b7-11ed-b908-571fef22d2ba\", message: \"This is a live-updating subscription!\"}) {\n    id\n  }\n}"}' <YOUR_PROJECT_GRAPHQL_ENDPOINT>

After entering the above command hitting enter, you should see the following output on your Console's API tab:

<Thumbnail src="/img/subscriptions/subscriptions_quickstart-cloud2.20.0.gif" alt="Hasura Scheduled Trigger architecture" width="1000" />

Recap

What just happened? Well, you just wrote your first subscription! You can now subscribe to live updates for a notification thread. Think of the possibilities in a real-world application: you can subscribe to live updates for a chat thread, a shopping cart, or a live leaderboard.

At the start, you created a subscription using the Hasura Console's API tab. This subscription returns the id field for all notifications with a user_id equal to the provided value. This allows us to receive new data, live from the server, rather than just a single response. So, as new notifications are inserted into the database - like we did with the curl command - the subscription will return them.