@apollo/client/core#createHttpLink TypeScript Examples

The following examples show how to use @apollo/client/core#createHttpLink. 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: configured-command.ts    From amplication with Apache License 2.0 6 votes vote down vote up
constructor(...args: [any, any]) {
    super(...args);

    if (!fs.existsSync(this.config.configDir))
      fs.mkdirSync(this.config.configDir, { recursive: true });

    if (fs.existsSync(this.configFilePath))
      this.configJSON = require(this.configFilePath);

    let serverUrl = this.configJSON[AMP_SERVER_URL];
    if (!serverUrl) {
      serverUrl = DEFAULT_SERVER_URL;
      this.setConfig(AMP_SERVER_URL, DEFAULT_SERVER_URL);
    }

    serverUrl = urlJoin(serverUrl, 'graphql');
    const httpLink = createHttpLink({
      uri: serverUrl,
      fetch,
    });

    const authLink = setContext((_, { headers }) => {
      // get the authentication token from config if it exists
      const token = this.getConfig('token');
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : '',
        },
      };
    });

    this.client.setLink(authLink.concat(httpLink));
  }
Example #2
Source File: test-runner.ts    From balancer-subgraph-v2 with MIT License 6 votes vote down vote up
runTestCases = async (groupName: string, testCases: TestCase[]): void => {
  const linkOptions = { uri: SUBGRAPH_QUERY_ENDPOINT, fetch };
  const link = createHttpLink(linkOptions);
  const cache = new InMemoryCache();
  let aClient = new ApolloClient({ link, cache });

  describe(`${groupName} resolvers`, () => {
    for (let testCase of testCases) {
      it(testCase.id, async () => {
        const res = await aClient.query({
          query: testCase.query,
          variables: testCase.variables || {},
        });
        expect(res).toMatchSnapshot();
      });
    }
  });
}
Example #3
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',
      },
    },
  };
}