Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do graphql and graphql subscriptions with svelte

Tags:

graphql

svelte

To do graphql queries and mutations ive had success with both fetch and svelte-apollo (see https://github.com/timhall/svelte-apollo)

I like the fech approach for its simplicity.

Svelte-apollo features subscriptions and I will try to get it to work.

But are there alternatives?

How do you consume graphql subscriptions with svelte?

like image 257
Jesper Ordrup Avatar asked May 09 '19 18:05

Jesper Ordrup


1 Answers

Heres my solution, using Apollo:

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { WebSocketLink } from 'apollo-link-ws';
import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';

const httpLink = new HttpLink({
  uri: 'http://localhost:3000/graphql'
});
const wsLink = new WebSocketLink({
  uri: `ws://localhost:3000/subscriptions`,
  options: {
    reconnect: true
  }
});


const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

After all that, you have your client set up. Next,

import gql from 'graphql-tag';

client.subscribe({
  query: gql`subscription { whatever }`
}).subscribe(result => console.log(result.data);
like image 112
abendigo Avatar answered Oct 09 '22 15:10

abendigo