Handle Subscriptions Plugin

Subscriptions are very different from queries or mutations, as it is considered a constant stream of events or data. Because of this, it requires special handling, villus implements the subscription support as a plugin for added flexibility and streamlining of the query execution process regardless of its type.

Options

The handleSubscriptions plugin requires only one option, a subscription forwarder, which is just a function that returns an observable.

vue<script setup>
import { useClient, handleSubscriptions, defaultPlugins } from 'villus';
import { createClient } from 'graphql-ws';

const wsClient = createClient({
  url: 'ws://localhost:9005/graphql',
});

const subscriptionsHandler = handleSubscriptions(operation => {
  return {
    subscribe: obs => {
      wsClient.subscribe(
        {
          query: operation.query,
          variables: operation.variables,
        },
        obs
      );

      return {
        unsubscribe: () => {
          // No OP
        },
      };
    },
  };
});

// in your setup
const client = useClient({
  url: 'http://localhost:4000/graphql',
  // Install the subscriptions handler
  use: [subscriptionsHandler, ...defaultPlugins()],
});
</script>

Code

You can check the source code for the handleSubscriptions plugin and use it as a reference to build your own