32.0.0 • Published 2 months ago

tachyon-relay v32.0.0

Weekly downloads
-
License
UNLICENSED
Repository
-
Last release
2 months ago

Tachyon Relay

A top-level configuration of Relay for consuming GQL at Twitch. tachyon-relay-build is a recommended companion to using this package outside of the Tachyon monorepo.

Usage

This package has been tested with Next.js and Create React App, but should also work elsewhere. See the example consumer for a simple working example.

Configuration

Call configureTachyonRelay at the entry point to your app to ensure the runtime has the right options set:

  • browserRetry: Should the client retry failed fetches in the browser (default: true)
  • clientId: The Twitch API Client-Id value of the consuming app (required)
  • errorsArrayIsFatal: Callback for handling the appearance of an errors array. If no function is passed, then any errors will be treated as failed fetches in line with the current guidance from the API team. This function will receive a copy of the errors array and the GraphQL query string with which to determine whether the application can proceed with the errors as listed
  • gqlEndpoint: The Twitch API Client-Id value of the consuming app (default: https://gql.twitch.tv/gql)
  • serverFetchTimeout: Timeout limit (ms) for fetches on the server (default: 1500)

Debug Mode

Debug mode (enabled by passing debug: true in the config options) triggers a few changes to package functionality:

  • makes the relay store globally available at window.getTachyonRelayStore
  • prints extended error information to the debug console
  • prints services associated with a GQL query to the debug console
  • enables GQL service-failure emulation, via an array of services passed into config under the failServices key

Creating A Relay Environment

This packages exposes an initEnvironment function for generating a proper Relay environment for making GraphQL requests against the Twitch API. On the server, it will return a new environment every time for SSR safety. In the browser it will return the same environment on each call since it assumes the browser is not a multi-tenant environment.

Performing GQL Query Requests With Hooks

The simplest way to make requests is using the Relay Hooks API. This requires putting a RelayEnvironmentProvider in your app's root, and then using hooks like useLazyLoadQuery to perform fetches as needed. You'll need to ensure you have a Suspense boundary in your app as well, to handle loading states while the fetch is performed.

const App: FC = () => {
  const relayEnvironment = useConst(initEnvironment);

  return (
    <RelayEnvironmentProvider environment={relayEnvironment}>
      <Suspense fallback={<MySpinner />}>
        <Foo />
      </Suspense>
    </RelayEnvironmentProvider>
  );
};

const Foo: FC = () => {
  const data = useLazyLoadQuery(myQuery, myQueryVariables);

  return <Bar info={data?.info} />;
};

Performing GQL Query Request With TachyonQueryRenderer (deprecated)

Note: Use new Relay hooks instead.

Relay's default QueryRenderer isn't entirely optimized for SSR, so this package exposes TachyonQueryRenderer which uses a much more streamlined implementation on the server, but it does require a properly hydrated store for SSR rendering because it completely skips any network activity. Use fetchQuery from react-relay to do this.

The 'Authorization' header must be set to make requests that require user authentication. This is set by providing the authorization object, which has token which accepts a string literal or retrieval function, and unauthorizedHandler which is invoked before retrying the request when the GraphQL endpoint returns a 401 Unauthorized.

Working With Ids In Relay

Providing External Object IDs To Relay

Relay requires that all objects have a globally unique ID in order to enable efficient and safe caching behavior. Because Twitch's GQL implementation does not guarantee object IDs are unique (some even intentionally collide), we have a number of custom utilities to build sanitize external IDs being provided to Relay such as when using for Query Variables.

For a full list of these, see the convertToSafe<Type>ID functions in the idConversion module.

Providing Relay Object Ids To Other Systems

When consuming Relay Object Ids in other systems such as event tracking or link building, use the convertToUnsafeID utility.

Validating Response Objects

Use the isValidObject helper to validate that a GQL Object is not null and has a type narrowed, non-null, id field.

GraphQL Preconnect

In order to speed up your first request in an SSR app, this package exposes a <GraphqlPreconnect/> component that should be rendered into the head of your html on the server. This signals the browser to negotiate an HTTPS connection to our GraphQL API, speeding up the first request when it is actually made.

Request Info

If you need to retrieve the RequestInfo GraphQL object in an SSR app, there is a fully contained framework for exposing that without having to augment the rest of your queries.

To do this, add the following to the root of your app:

<RequestInfoRoot environment={relayEnvironment} />

Then use the withRequestInfo HOC or the useRequestInfo hook to access the data. This will only provide the data once on the client.