Subscription

Agent stream subscription

To subscribe to a Hasura server and receive real-time updates for the /agent/session collection with parameters like agent and session_id, you can use GraphQL subscriptions. Here's how to do it using JavaScript and the graphql-ws library, which is common for working with subscriptions in Hasura.

First, make sure you have the necessary dependencies installed. If you don't have them, you can install them using npm or yarn:

npm install graphql graphql-ws

Then, you can create a JavaScript file that sets up a WebSocket connection and subscribes to changes in /agent/session:

const { createClient } = require('graphql-ws');

const client = createClient({
  url: 'wss://your-hasura-instance.uncodie.com/v1/graphql',
  connectionParams: {
    headers: {
      'Authorization': 'Bearer your-access-token'
    }
  }
});

const query = `
  subscription getAgentSession($agent: String!, $session_id: String!) {
    agent_session(where: {agent: {_eq: $agent}, session_id: {_eq: $session_id}}) {
      agent
      session_id
      // include other fields you need
    }
  }
`;

const variables = {
  agent: 'your-agent',
  session_id: 'your-session-id'
};

client.subscribe(
  { query, variables },
  {
    next(data) {
      console.log('Data received:', data);
    },
    error(err) {
      console.error('Error:', err);
    },
    complete() {
      console.log('Subscription complete');
    },
  }
);

Replace 'wss://your-hasura-instance.uncodie.com/v1/graphql' with the URL of your Hasura instance and adjust 'your-access-token' with your API access token.

This script subscribes to changes in the specified table or collection (agent_session) filtering by agent and session_id. Whenever there is a change that meets these filters, you will receive a notification through the WebSocket and the next function will be executed.

Make sure to modify the variables and query fields according to the details of your Hasura schema and the data you need to monitor.

Last updated

Was this helpful?