@apollo/client/link/ws#WebSocketLink TypeScript Examples

The following examples show how to use @apollo/client/link/ws#WebSocketLink. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
createApolloClient = () => {
  const subscriptionLink = new WebSocketLink({
    uri: QUERY_NODE_GRAPHQL_SUBSCRIPTION_URL,
    options: {
      reconnect: true,
      reconnectionAttempts: 5,
    },
  })

  const orionLink = new HttpLink({ uri: ORION_GRAPHQL_URL })
  const batchedOrionLink = new BatchHttpLink({ uri: ORION_GRAPHQL_URL, batchMax: 10 })

  const orionSplitLink = split(
    ({ operationName }) => {
      return operationName === 'GetVideos' || operationName === 'GetVideoCount'
    },
    batchedOrionLink,
    orionLink
  )

  const operationSplitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query)
      return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
    },
    subscriptionLink,
    orionSplitLink
  )

  return new ApolloClient({ cache, link: operationSplitLink })
}
Example #2
Source File: clientConfig.ts    From OpenVolunteerPlatform with MIT License 6 votes vote down vote up
wsLink = new WebSocketLink({
  uri: wsUri,
  options: {
    reconnect: true,
    lazy: true,
    // returns auth header or empty string
    connectionParams: async () => (await getAuthHeader())
  },
})
Example #3
Source File: apolloClient.tsx    From nextjs-hasura-boilerplate with MIT License 6 votes vote down vote up
createWSLink = (token: string) => {
  return new WebSocketLink(
    new SubscriptionClient(
      process.env.NEXT_PUBLIC_WS_URL,
      {
        lazy: true,
        reconnect: true,
        connectionParams: async () => {
          return {
            headers: { Authorization: `Bearer ${token}` },
          };
        },
      },
      ws
    )
  );
}
Example #4
Source File: index.ts    From fullstack-starterkit with MIT License 6 votes vote down vote up
function configureApolloClient(config: Config): ApolloClient<NormalizedCacheObject> {
  const httpLink = new HttpLink({ uri: config.endpoints.https });

  const wsLink = new WebSocketLink({
    uri: config.endpoints.wss,
    options: { reconnect: true }
  });

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

  const client = new ApolloClient({
    link: ApolloLink.from([
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors) {
          graphQLErrors.forEach(({ message, locations, path }) =>
            console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
          );
        }

        if (networkError) {
          console.log(`[Network error]: ${networkError}`);
        }
      }),
      link
    ]),
    cache: new InMemoryCache()
  });

  return client;
}
Example #5
Source File: index.tsx    From ledokku with MIT License 6 votes vote down vote up
wsLink = new WebSocketLink({
  uri: `${config.serverWsUrl}/graphql`,
  options: {
    reconnect: true,
    connectionParams: () => {
      return {
        token: localStorage.getItem('accessToken'),
      };
    },
  },
})
Example #6
Source File: apolloClient.tsx    From nextjs-hasura-fullstack with MIT License 6 votes vote down vote up
createWSLink = (token: string) => {
  return new WebSocketLink(
    new SubscriptionClient(
      process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8080/v1/graphql',
      {
        lazy: true,
        reconnect: true,
        connectionParams: async () => {
          return {
            headers: { Authorization: `Bearer ${token}` },
          }
        },
      },
      ws,
    ),
  )
}
Example #7
Source File: index.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
wsLink = new WebSocketLink({
  uri: searchParams.get('subscriptions_url') ?? 'ws://localhost:3500/graphql',
  options: {
    reconnect: true,
    lazy: true,
  },
})
Example #8
Source File: main.ts    From vueconf-london with MIT License 5 votes vote down vote up
wsLink = new WebSocketLink({
  uri: "ws://" + GRAPHQL_ENDPOINT,
  options: {
    reconnect: true,
    lazy: true,
  },
})
Example #9
Source File: api.service.ts    From etherspot-sdk with MIT License 5 votes vote down vote up
protected onInit(): void {
    const httpLink = new HttpLink({
      fetch,
      uri: buildApiUri(this.options, 'http'),
    });

    const wsLink = new WebSocketLink({
      webSocketImpl: WebSocket,
      uri: buildApiUri(this.options, 'ws', 'graphql'),
      options: {
        reconnect: true,
        lazy: true,
      },
    });

    const authLink = setContext(async () => {
      const {
        accountService, //
        sessionService,
        projectService,
      } = this.services;

      return {
        headers: {
          ...accountService.headers,
          ...sessionService.headers,
          ...projectService.headers,
        },
      };
    });

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

    this.apolloClient = new ApolloClient({
      link,
      cache: this.cache,
    });
  }
Example #10
Source File: Shell.tsx    From dh-web with GNU General Public License v3.0 5 votes vote down vote up
Shell: FC<ShellProperties> = ({ children }: ShellProperties) => {

    // get the authentication token from local storage if it exists
    const authToken = useSelector(getAuthenticationToken);

    const bearerString = authToken && `Bearer ${authToken}`;
    // cross platform web socketing triage (tldr use node lib on server and web lib on browser)
    const webSocketImplementation = process.browser ? WebSocket : ws;

    const wsLink = new WebSocketLink({
        uri: "wss://api.dogehouse.online/graphql",
        options: {
            reconnect: true,
            lazy: true,
            timeout: 3000,
            connectionParams: {
                authorization: bearerString
            }
        },
        webSocketImpl: webSocketImplementation
    });

    const httpLink = createHttpLink({
        uri: "https://api.dogehouse.online/graphql",
    });

    const authLink = setContext((_, { headers }) => {
        // return the headers to the context so httpLink can read them
        return {
            headers: {
                ...headers,
                authorization: bearerString,
            }
        };
    });

    const splitLink = split(
        ({ query }) => {
            const definition = getMainDefinition(query);
            return (
                definition.kind === "OperationDefinition" &&
                definition.operation === "subscription"
            );
        },
        wsLink,
        (authLink.concat(httpLink)),
    );

    const client = new ApolloClient({
        link: from([errorLink, splitLink]),
        cache: new InMemoryCache(),
    });

    return (
        <ThemeProvider theme={DarkTheme}>
            <ApolloProvider client={client}>
                <GlobalStyle />
                <Head>
                    <link rel="preconnect" href="https://fonts.gstatic.com" />
                    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet" />
                </Head>
                <Wrapper>
                    <NoSsr>
                        {
                            children
                        }
                    </NoSsr>
                </Wrapper>
            </ApolloProvider>
        </ThemeProvider>
    );
}
Example #11
Source File: withApollo.tsx    From NextJS-NestJS-GraphQL-Starter with MIT License 5 votes vote down vote up
withApolloWithSubscriptions = nextWithApollo(
  ({ initialState, headers, ...rest }) => {
    const clientId = nanoid();

    const wsLink = !IS_SERVER
      ? new WebSocketLink({
          uri: WEBSOCKET_API_URL,
          options: {
            reconnect: true,
            connectionParams: {
              clientId
            }
          }
        })
      : null;

    const httpLink = new HttpLink({
      uri: IS_SERVER ? SERVER_API_ENDPOINT : BROWSER_API_ENDPOINT,
      headers: {
        ...headers
      },
      credentials: 'include'
    });

    /*
     * Only create a split link on the browser
     * The server can not use websockets and is therefore
     * always a http link
     */
    const splitLink = !IS_SERVER
      ? split(
          ({ query }) => {
            const definition = getMainDefinition(query);
            return (
              definition.kind === 'OperationDefinition' &&
              definition.operation === 'subscription'
            );
          },
          wsLink,
          httpLink
        )
      : httpLink;

    return new ApolloClient({
      ssrMode: IS_SERVER,
      link: splitLink,
      cache: new InMemoryCache().restore(initialState || {}),
      // A hack to get ctx oin the page's props on the initial render
      // @ts-ignore
      defaultOptions: { ...rest, clientId }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page
            {...props}
            {...props.apollo.defaultOptions.ctx}
            clientId={props.apollo.defaultOptions.clientId}
          />
        </ApolloProvider>
      );
    }
  }
)
Example #12
Source File: graphql.module.ts    From one-platform with MIT License 4 votes vote down vote up
export function createApollo(): ApolloClientOptions<any> {
  const wsClient = new WebSocketLink({
    uri: environment.WS_URL,
    options: {
      reconnect: true,
      inactivityTimeout: 0,
      reconnectionAttempts: 10,
      connectionParams: {
        Authorization: `Bearer ${window.OpAuthHelper.jwtToken}`,
      },
    },
  });

  const httpLink = createHttpLink({
    uri: environment.API_URL,
  });

  const authLink = setContext((_, { headers }) => {
    // get the authentication token from local storage if it exists
    const token = window.OpAuthHelper.jwtToken;
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        Authorization: token ? `Bearer ${token}` : '',
      },
    };
  });

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      );
    },
    wsClient,
    authLink.concat(httpLink)
  );
  const retry = new RetryLink({
    delay: {
      initial: 500,
      max: Infinity,
      jitter: false,
    },
    attempts: {
      max: 5,
      retryIf: (_error, _operation) => !!_error,
    },
  }) as any;

  const error = onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, locations, path }) =>
        console.log(
          `[GraphQL error]: Message: ${JSON.stringify(
            message
          )}, Location: ${JSON.stringify(locations)}, Path: ${JSON.stringify(
            path
          )}`
        )
      );
    }
    if (networkError && networkError['status'] === 0) {
      this.isCertificateError.next(true);
      console.log(`[Network error]: ${JSON.stringify(networkError)}`);
    }
  });

  const link = WebSocketLink.from([retry, error, splitLink]);

  return {
    name: 'Lighthouse GraphQL Client',
    version: '0.0.1',
    link,
    cache: new InMemoryCache({
      addTypename: false,
    }),
    defaultOptions: {
      watchQuery: {
        fetchPolicy: 'cache-and-network',
        errorPolicy: 'all',
      },
    },
  };
}