@apollo/client#HttpLink TypeScript Examples

The following examples show how to use @apollo/client#HttpLink. 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: apolloClient.ts    From next-page-tester with MIT License 6 votes vote down vote up
function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: new HttpLink({
      uri: 'https://nextjs-graphql-with-prisma-simple.vercel.app/api', // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch,
    }),
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            allPosts: concatPagination(),
          },
        },
      },
    }),
  });
}
Example #2
Source File: index.tsx    From Insomniac-NextJS-boilerplate with MIT License 6 votes vote down vote up
function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: new HttpLink({
      uri: process.env.NEXT_PUBLIC_API_URL, // Server URL (must be absolute)
    }),
    cache: new InMemoryCache(),
  });
}
Example #3
Source File: initApollo.tsx    From nft-marketplace with European Union Public License 1.2 6 votes vote down vote up
function create(initialState) {
  const httpLink = new HttpLink({
    uri: GRAPHQL_ENDPOINT,
    credentials: 'same-origin',
  });

  return new ApolloClient({
    connectToDevTools: process.browser,
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    link: httpLink,
    cache: new InMemoryCache({ possibleTypes }).restore(initialState || {}),
  });
}
Example #4
Source File: withApollo.tsx    From NextJS-NestJS-GraphQL-Starter with MIT License 6 votes vote down vote up
withApollo = nextWithApollo(
  ({ initialState, headers, ...rest }) => {
    const httpLink = new HttpLink({
      uri: IS_SERVER ? SERVER_API_ENDPOINT : BROWSER_API_ENDPOINT,
      headers: {
        ...headers
      },
      credentials: 'include'
    });

    return new ApolloClient({
      ssrMode: IS_SERVER,
      link: httpLink,
      cache: new InMemoryCache().restore(initialState || {}),
      // A hack to get ctx oin the page's props on the initial render
      // @ts-ignore
      defaultOptions: { ...rest }
    });
  },
  {
    render: ({ Page, props }) => {
      return (
        <ApolloProvider client={props.apollo}>
          <Page {...props} {...props.apollo.defaultOptions.ctx} />
        </ApolloProvider>
      );
    }
  }
)
Example #5
Source File: apollo-client.ts    From beancount-mobile with MIT License 6 votes vote down vote up
link = middlewareLink.concat(
  ApolloLink.from([
    onErrorLink,
    new HttpLink({
      uri: getEndpoint("api-gateway/"),
      fetch,
    }),
  ])
)
Example #6
Source File: apolloClient.tsx    From nextjs-hasura-fullstack with MIT License 6 votes vote down vote up
createHttpLink = (token: string) => {
  const httpLink = new HttpLink({
    uri: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080/v1/graphql',
    credentials: 'include',
    headers: { Authorization: `Bearer ${token}` },
    fetch,
  })
  return httpLink
}
Example #7
Source File: App.tsx    From graphql-schema-registry with MIT License 6 votes vote down vote up
App = ({ api }: AppProps) => {
	const config = createConfig(api);

	const client = new ApolloClient({
		cache: new InMemoryCache(),
		link: new HttpLink({
			uri: config.grapqhlEndpoint,
			credentials: 'include',
		}),
	});

	return (
		<GlobalConfigContext.Provider value={config}>
			<ApolloProvider client={client}>
				<Main />
			</ApolloProvider>
		</GlobalConfigContext.Provider>
	);
}
Example #8
Source File: client.ts    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
getClient = (): ApolloClient<NormalizedCacheObject> => {
  if (!client) {
    const config = getConfig() as NextConfigType

    if (!config) return client

    const { publicRuntimeConfig, serverRuntimeConfig } = config

    client = new ApolloClient<NormalizedCacheObject>({
      cache: new InMemoryCache(),
      link: from([
        setContext((request, context) => {
          const headers: { [key: string]: string } = {}

          if (process.browser) {
            const access = localStorage.getItem('access')

            if (access) {
              headers.authorization = `Bearer ${access}`
            }
          }

          return {
            headers,
          }
        }),
        new HttpLink({
          uri: serverRuntimeConfig.endpoint || publicRuntimeConfig.endpoint,
        }),
      ]),
    })
  }

  return client
}
Example #9
Source File: nextApollo.ts    From liferay-grow with MIT License 6 votes vote down vote up
function createApolloClient() {
  const Authorization = getToken();

  return new ApolloClient({
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            allPosts: concatPagination(),
          },
          keyFields: ['id'],
        },
      },
    }),
    link: new HttpLink({
      credentials: 'same-origin',
      headers: {
        Authorization,
      },
      uri: `${baseURL}/graphql`,
    }),
    ssrMode: typeof window === 'undefined',
  });
}
Example #10
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 #11
Source File: apolloClient.tsx    From nextjs-hasura-boilerplate with MIT License 6 votes vote down vote up
createHttpLink = (token: string) => {
  const getHttpUri = () => {
    if (process.env.NODE_ENV === "production") {
      return process.env.NEXT_PUBLIC_API_URL;
    }

    return process.browser
      ? process.env.NEXT_PUBLIC_CSR_API_URL
      : process.env.NEXT_PUBLIC_SSR_API_URL;
  };

  const httpLink = new HttpLink({
    uri: getHttpUri(),
    credentials: "include",
    headers: { Authorization: `Bearer ${token}` },
    fetch,
  });
  return httpLink;
}
Example #12
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 #13
Source File: index.ts    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
httpLink = new HttpLink({
  uri: searchParams.get('api_url') ?? 'http://localhost:3500/graphql',
  credentials: 'include',
  headers: () => ({
    'Accept-Language': 'en',
  }),
})
Example #14
Source File: index.tsx    From game-store-monorepo-app with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  uri: process.env.NX_API_URL,
})
Example #15
Source File: index.tsx    From ledokku with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  uri: `${config.serverUrl}/graphql`,
})
Example #16
Source File: apolloClient.ts    From bouncecode-cms with GNU General Public License v3.0 5 votes vote down vote up
function createApolloClient(req) {
  const isSsr = typeof window === 'undefined';
  const uri = isSsr ? `http://localhost:${PORT}/graphql` : '/graphql';

  const getToken = async ({access_token, refresh_token}) => {
    if (access_token) {
      try {
        const {exp}: any = jwt.decode(access_token);

        if (Date.now() < (exp - 600) * 1000) {
          return access_token;
        }
      } catch (e) {}
    }

    if (refresh_token) {
      const res = await fetch(uri, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          operationName: null,
          query: gql`
            mutation($refreshToken: String!) {
              refreshToken(refreshToken: $refreshToken) {
                access_token
              }
            }
          `.loc.source.body,
          variables: {
            refreshToken: refresh_token,
          },
        }),
      });

      const {data} = await res.json();
      const access_token = data.token.access_token;
      storeToken(null, {access_token});
      return access_token;
    }
  };

  const httpLink = new HttpLink({
    uri, // Server URL (must be absolute)
    credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
    fetch,
  });

  const authLink = setContext(async (_, {headers}) => {
    const {access_token, refresh_token} = parseCookies(req);
    let token;

    try {
      token = await getToken({access_token, refresh_token});
    } catch (e) {}

    if (token) {
      return {
        headers: {
          ...headers,
          authorization: `Bearer ${token}`,
        },
      };
    } else {
      return {headers};
    }
  });

  // The `ctx` (NextPageContext) will only be present on the server.
  // use it to extract auth headers (ctx.req) or similar.
  return new ApolloClient({
    ssrMode: isSsr,
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
  });
}
Example #17
Source File: clientConfig.ts    From OpenVolunteerPlatform with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  uri: httpUri,
})
Example #18
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 #19
Source File: configureGraphQL.ts    From knests with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  fetch,
  uri: SERVER,
})
Example #20
Source File: graphql.ts    From index-ui with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
  }),
  cache: new InMemoryCache(),
})
Example #21
Source File: ApolloProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 4 votes vote down vote up
ApolloProvider: FC = ({ children }) => {
  const addErrorNotification = useAddErrorNotification()
  const [persisted, setPersisted] = useState(false)
  const network = useNetwork()
  const previousChainId = usePrevious(network.chainId)
  const networkChanged = previousChainId && network.chainId !== previousChainId

  // Serialized array of failed endpoints to be excluded from the client
  const [failedEndpoints] = useState<string>('')

  const handleError = useCallback(
    (message: string, error?: unknown): void => {
      console.error(message, error)

      // Not significant at the moment; falls back to the hosted service
      if (message.includes('Exhausted list of indexers')) return

      let sanitizedError: string = message
      let body: string | undefined
      if (message.includes('Failed to query subgraph deployment')) {
        sanitizedError = `Subgraph: ${message.split(': ')[1] ?? message}`
      }

      if ((error as { operation?: Operation })?.operation?.operationName) {
        body = `Subgraph: ${(error as { operation: Operation }).operation.operationName}`
      }

      addErrorNotification(sanitizedError, body)
    },
    [addErrorNotification],
  )

  useEffect(() => {
    Promise.all(
      Object.keys(caches).map(clientName =>
        persistCache({
          cache: caches[clientName as keyof ApolloClients] as never,
          storage: window.localStorage as never,
          key: `${network.chainId}-${clientName}`,
        }),
      ),
    )
      .catch(_error => {
        console.warn('Cache persist error', _error)
      })
      .finally(() => {
        setPersisted(true)
      })
  }, [setPersisted, network.chainId])

  const apollo = useMemo<{ ready: true; clients: ApolloClients } | { ready: false }>(() => {
    if (!persisted) return { ready: false }

    // const _failedEndpoints = failedEndpoints.split(',')

    const errorLink = onError(error => {
      const { networkError, graphQLErrors } = error
      if (graphQLErrors) {
        graphQLErrors.forEach(({ message, ..._error }) => {
          // if (_failedEndpoints.includes(ctx.uri)) return

          handleError(message, error)

          // On any GraphQL error, mark the endpoint as failed; this may be
          // excessive, but failed endpoints are merely deprioritised rather than
          // excluded completely.
          // _failedEndpoints.push(ctx.uri)
        })
      }

      if (networkError) {
        handleError(networkError.message, error)
      }
      // setFailedEndpoints(_failedEndpoints.join(','))
    })

    const retryIf = (error: { statusCode: number }) => {
      const doNotRetryCodes = [500, 400]
      return !!error && !doNotRetryCodes.includes(error.statusCode)
    }

    const clients = (Object.keys(caches) as AllGqlEndpoints[])
      .map<[AllGqlEndpoints, ApolloClient<NormalizedCacheObject>]>(name => {
        if (!Object.prototype.hasOwnProperty.call(network.gqlEndpoints, name)) {
          return [name, dummyClient]
        }

        const endpoints = network.gqlEndpoints[name as keyof typeof network['gqlEndpoints']]
        const preferred = endpoints.filter(endpoint => !failedEndpoints.split(',').includes(endpoint))[0]
        const fallback = endpoints[0] // There is always a fallback, even if it failed
        const endpoint = preferred ?? fallback
        const timeoutLink = new ApolloLinkTimeout(30000)

        const endpointNameLink = new ApolloLink((operation, forward) => {
          operation.extensions.endpointName = name
          return forward(operation)
        })
        const httpLink = new HttpLink({ uri: endpoint })
        const retryLink = new RetryLink({ delay: { initial: 1e3, max: 5e3, jitter: true }, attempts: { max: 1, retryIf } })
        const link = ApolloLink.from([endpointNameLink, networkStatusLink, retryLink, timeoutLink, errorLink, httpLink])
        const client = new ApolloClient<NormalizedCacheObject>({
          cache: caches[name],
          link,
          defaultOptions: {
            watchQuery: {
              fetchPolicy: 'cache-and-network',
              errorPolicy: 'all',
            },
            query: {
              fetchPolicy: 'cache-first',
              errorPolicy: 'all',
            },
          },
        })

        return [name, client]
      })
      .reduce<ApolloClients>(
        (prev, [clientName, client]) => ({ ...prev, [clientName as keyof ApolloClients]: client }),
        {} as ApolloClients,
      )

    return { ready: true, clients }
  }, [persisted, failedEndpoints, handleError, network])

  useEffect(() => {
    // Reset caches that can have conflicting keyFields on network change
    // This prevents cached data from a previously selected network being used
    // on a newly-selected network
    if (networkChanged && (apollo as { clients: ApolloClients }).clients) {
      ;(apollo as { clients: ApolloClients }).clients.blocks.resetStore().catch(error => {
        console.error(error)
      })
    }
  }, [apollo, networkChanged])

  return apollo.ready ? <apolloClientsCtx.Provider value={apollo.clients}>{children}</apolloClientsCtx.Provider> : <Skeleton />
}