httpLinkForNhost function

Link httpLinkForNhost(
  1. String nhostGqlEndpointUrl,
  2. HasuraAuthClient nhostAuth, {
  3. Client? httpClientOverride,
  4. Map<String, String>? defaultHeaders = const {},
})

Creates an HTTP link that configures automatically based on nhostAuth's authentication state.

nhostGqlEndpointUrl can be found at NhostClient.gqlEndpointUrl.

defaultHeaders (optional) A set of headers that will be provided with all requests passing through the link.

httpClientOverride (optional) can be provided to customize the network request, such as to configure proxies, introduce interceptors, etc.

Implementation

Link httpLinkForNhost(
  String nhostGqlEndpointUrl,
  HasuraAuthClient nhostAuth, {
  http.Client? httpClientOverride,
  Map<String, String>? defaultHeaders = const {},
}) {
  final unauthenticatedLink = HttpLink(
    nhostGqlEndpointUrl,
    httpClient: httpClientOverride,
    defaultHeaders: defaultHeaders ?? const {},
  );

  // Introduce an Authorization header
  final addAuthenticationLink = Link.function((request, [forward]) {
    if (nhostAuth.authenticationState == AuthenticationState.signedIn) {
      request = request.updateContextEntry<HttpLinkHeaders>(
        (entry) => HttpLinkHeaders(
          headers: {
            ...?entry?.headers,
            'Authorization': 'Bearer ${nhostAuth.accessToken}',
          },
        ),
      );
    }

    return forward!(request);
  });

  return Link.concat(addAuthenticationLink, unauthenticatedLink);
}