How to use apollo-link-ws - 10 common examples

To help you get started, we’ve selected a few apollo-link-ws examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alltogethernow / web / src / modules / apollo.js View on Github external
import { version } from '../../package.json'
import { GET_CHANNELS } from '../queries'

// Create an http link:
const httpLink = new HttpLink({
  uri: process.env.REACT_APP_SERVER || 'http://localhost:4000',
  includeExtensions: true,
  headers: {
    authorization: localStorage.getItem('token'),
    'client-name': 'Together [web]',
    'client-version': version,
  },
})

// Create a WebSocket link:
const wsLink = new WebSocketLink({
  uri:
    process.env.REACT_APP_SUBSCRIPTION_SERVER || 'ws://localhost:4000/graphql',
  options: {
    reconnect: true,
    timeout: 30000,
    connectionParams: {
      authToken: localStorage.getItem('token'),
    },
  },
})

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
github fanout / apollo-serverless-demo / src / WebSocketApolloClient.ts View on Github external
const WebSocketApolloClient = ({
  url,
  subscriptionsUrl,
}: IApolloServerUrlInfo) => {
  const httpLink = createHttpLink({
    fetch: async (input, init) => {
      const response = await fetch(input, init);
      return response;
    },
    uri: url,
  });
  const wsLink = new WebSocketLink({
    options: {
      reconnect: true,
      timeout: 999999999,
    },
    uri: subscriptionsUrl,
    webSocketImpl: WebSocket,
  });
  const link = split(
    // split based on operation type
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === "OperationDefinition" &&
        definition.operation === "subscription"
      );
    },
github msand / InfiniDraw / lib / init-apollo.js View on Github external
function create(initialState, native) {
  const httpLink = new HttpLink({
    uri: 'https://api.graph.cool/simple/v1/cjh2g1fxn6gsw0108o6ud01ms', // Server URL (must be absolute)
    credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
  });
  const wsLink =
    (process.browser || native) &&
    new WebSocketLink({
      uri: 'wss://subscriptions.graph.cool/v1/cjh2g1fxn6gsw0108o6ud01ms',
      options: {
        reconnect: true,
      },
    });
  const link =
    !process.browser && !native
      ? httpLink
      : split(
          ({ query }) => {
            const { kind, operation } = getMainDefinition(query);
            return (
              kind === 'OperationDefinition' && operation === 'subscription'
            );
          },
          wsLink,
github goldo / gcp-pubsub-debugger / src / apolloClient.js View on Github external
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { split } from 'apollo-link'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'

// Create an http link:
const httpLink = new HttpLink({
  uri: `http://localhost:${process.env.REACT_APP_SERVER_PORT}`,
})

// Create a WebSocket link:
const wsLink = new WebSocketLink({
  uri: `ws://localhost:${process.env.REACT_APP_SERVER_PORT}/`,
  options: {
    reconnect: true,
  },
})

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
  // split based on operation type
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query)
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  httpLink
github rshk / yawc / web / src / lib / apollo.js View on Github external
}
    return createHttpLink(config);
})();


const authLink = setContext((_, {headers: extraHeaders}) => {
    const token = getToken();
    const headers = {...extraHeaders};
    if (token) {
        headers.authorization = `Bearer ${token}`;
    }
    return {headers};
});


const wsLink = new WebSocketLink({
    uri: WEBSOCKET_URL,
    options: {
        reconnect: true,
        connectionParams: {
            authToken: getToken(),
        },
    }
});


// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const link = split(
    // split based on operation type
    ({ query }) => {
        const {kind, operation} = getMainDefinition(query);
github Pitchlyapp / meteor-apollo2 / client / main.js View on Github external
/* Initialize Apollo Client for GraphQL */

// You might want to set these manually if you're running your server somewhere else
const httpUri = Meteor.absoluteUrl('graphql'); // http://localhost:3000/graphql
const wsUri = Meteor.absoluteUrl('subscriptions').replace(/^http/, 'ws'); // ws://localhost:3000/subscriptions

// Apollo 2.0 now uses the extensible "ApolloLink" (the following does not rely on Meteor)

const link = ApolloLink.split(
  operation => {
  	const operationAST = getOperationAST(operation.query, operation.operationName);
  	return !!operationAST && operationAST.operation === 'subscription';
  },
  new WebSocketLink({
		uri: wsUri,
		options: {
			reconnect: true, // tells client to reconnect websocket after being disconnected (which will happen after a hot-reload)
      // // might be helpful if you want to carry login state from client
      // // it is recommended you use the secure version of websockets (wss) when transporting sensitive login information
			// connectionParams: {
			// 	authToken: localStorage.getItem("Meteor.loginToken")
			// }
		}
	}),
  new HttpLink({ uri: httpUri })
);

const cache = new InMemoryCache(window.__APOLLO_STATE);

const client = new ApolloClient({
github okgrow / advanced-graphql / web / src / client.js View on Github external
});

const hasSubscriptionOperation = operation =>
  operation.query.definitions.reduce(
    (result, definition) => result || definition.operation === 'subscription',
    false
  );

// http://localhost:8080 is put behind a proxy by webpack (cors)
const uri = '/graphql';

const link = ApolloLink.from([
  errorLink,
  authLink.split(
    hasSubscriptionOperation,
    new WsLink({
      uri: 'ws://localhost:8081/graphql',
      options: { reconnect: true },
    }),
    new HttpLink({ uri })
  ),
]);

const cache = new Cache();

const client = new ApolloClient({
  link,
  cache: cache.restore(window.__APOLLO_STATE__ || {}),
});

export default () => (
github loic-carbonne / realtime-notifications-apollo-graphql / frontend / src / index.js View on Github external
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { ApolloProvider } from 'react-apollo'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { split } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';

const httpLink = new HttpLink({ uri: 'http://localhost:4000/graphql' });

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/subscriptions`,
  options: {
    reconnect: true
  }
});

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink,
);

const client = new ApolloClient({
github prisma-labs / graphql-playground / packages / graphql-playground-react / src / state / sessions / fetchingSagas.ts View on Github external
uri: session.endpoint,
    headers,
    credentials,
  })

  if (!subscriptionEndpoint) {
    return { link: httpLink }
  }

  const subscriptionClient = new SubscriptionClient(subscriptionEndpoint, {
    timeout: 20000,
    lazy: true,
    connectionParams,
  })

  const webSocketLink = new WebSocketLink(subscriptionClient)
  return {
    link: ApolloLink.split(
      operation => isSubscription(operation),
      webSocketLink as any,
      httpLink,
    ),
    subscriptionClient,
  }
}
github peterj / shortly / src / index.js View on Github external
const authHeader = token ? `Bearer ${token}` : null;
  operation.setContext({
    headers: {
      authorization: authHeader
    }
  });
  return forward(operation);
});

const httpLink = new HttpLink({
  uri: GRAPHQL_ENDPOINT
});

const httpLinkWithToken = apolloLinkWithToken.concat(httpLink);

const wsLink = new WebSocketLink({
  uri: SUBSCRIPTIONS_ENDPOINT,
  options: {
    reconnect: true
  }
});

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLinkWithToken
);

const client = new ApolloClient({

apollo-link-ws

WebSocket transport layer for GraphQL

MIT
Latest version published 5 years ago

Package Health Score

62 / 100
Full package analysis

Popular apollo-link-ws functions

Similar packages