npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@os-team/relay-network-creator

v1.2.19

Published

Super tiny network layer for Relay. Works in the browser, Node.js, and React Native. Supports aborting a request and tracking the upload progress.

Downloads

111

Readme

@os-team/relay-network-creator NPM version BundlePhobia

Super tiny network layer for Relay. Works in the browser, Node.js, and React Native. Supports aborting a request and tracking the upload progress.

Installation

Step 1. Install the package

Install the package using the following command:

yarn add @os-team/relay-network-creator

It depends on relay-runtime (in peerDependencies), so if you haven't installed it yet, do so with the following command:

npx install-peerdeps @os-team/relay-network-creator

Step 2. Create a Relay Network

To create a Relay Network call the createRelayNetwork function and pass the URL to your API.

import createRelayNetwork from '@os-team/relay-network-creator';

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
});

Creating a Relay Environment may look like this:

import { Environment, RecordSource, Store } from 'relay-runtime';
import createRelayNetwork from '@os-team/relay-network-creator';

const url =
  process.env.NODE_ENV === 'production'
    ? 'https://api.domain.com/graphql'
    : 'http://localhost:4000/graphql';

let environment: Environment;

const createRelayEnvironment = (): Environment => {
  if (!environment) {
    environment = new Environment({
      network: createRelayNetwork({
        url,
        timeout: 30000,
      }),
      store: new Store(new RecordSource()),
    });
  }
  return environment;
};

export default createRelayEnvironment;

Usage

Setting the method

By default, all requests sent using the POST method, but you can change it as follows:

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  method: 'GET',
});

Setting headers

You can specify the headers that will be sent with any request.

Let's look at an example with adding the same authorization header to each request. This may be necessary for the admin panel, which should make authorized requests to the API.

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  headers: {
    Authorization: 'Bearer admin_key',
  },
});

Setting the timeout

You can set the timeout to abort a request if it takes more than N ms:

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  timeout: 30000, // 30 seconds
});

In this case, if the request lasts longer than 30 seconds, the request will be aborted and an error will occur. If the request uploads a file, the timeout will be ignored to allow a user to upload large files.

You can also specify your own error message:

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  timeout: 30000,
  timeoutMessage: 'Request timeout',
});

Aborting a request

Create the abortable object and pass it to the cache config. When you call the abortable.abort() function, the Relay Network will abort the request.

import {
  createAbortable,
  RelayNetworkCacheConfig,
} from '@os-team/relay-network-creator';

const FileUpload: React.FC = () => {
  const env = useRelayEnvironment();
  const abortable = useMemo(() => createAbortable(), []);

  const upload = useCallback(
    (file: File) => {
      const cacheConfig: RelayNetworkCacheConfig = {
        abortable,
      };
      const commit = commitMutation(env, {
        mutation: graphql`
          mutation FileUploadMutation($input: UploadFileInput!) {
            uploadFile(input: $input) {
              id
            }
          }
        `,
        variables: {
          input: {
            file: null,
          },
        },
        uploadables: {
          file,
        },
        cacheConfig,
      });
    },
    [commit, abortable]
  );

  return null; // Call `abortable.abort()` in your component to abort the request
};

You can specify your own error message as follows:

createAbortable('Request aborted');

Tracking the upload progress

Create the onUploadProgress callback and pass it to the cache config. The Relay Network will call this callback each time, the upload progress was updated.

import { RelayNetworkCacheConfig } from '@os-team/relay-network-creator';

const FileUpload: React.FC = () => {
  const [progress, setProgress] = useState(0);

  const onUploadProgress = useCallback(({ percent }) => {
    setProgress(percent);
  }, []);

  const upload = useCallback(
    (file: File) => {
      const cacheConfig: RelayNetworkCacheConfig = {
        onUploadProgress,
      };
      const commit = commitMutation(env, {
        mutation: graphql`
          mutation FileUploadMutation($input: UploadFileInput!) {
            uploadFile(input: $input) {
              id
            }
          }
        `,
        variables: {
          input: {
            file: null,
          },
        },
        uploadables: {
          file,
        },
        cacheConfig,
      });
    },
    [commit, onUploadProgress]
  );

  return null; // Use `progress` in your component
};

Middlewares

Middlewares allows you to modify any request or response. You can use existing middlewares or create your own.

Existing middlewares

All middlewares will have the prefix relay-network-mw-, so you can see any middlewares in npm by this prefix.

The following shared middlewares are currently available:

For example, you can add file upload support as follows:

import createRelayNetwork from '@os-team/relay-network-creator';
import upload from '@os-team/relay-network-mw-upload';

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  middlewares: [upload],
});

Creating your own middlewares

Most often, you need to change the request parameters. Using middlewares you can modify:

  • url and method for example, to make specific requests to another API.
  • headers for example, to add a user authorization key to requests.
  • timeout and timeoutMessage for example, to set a custom timeout and error message for some requests.
  • body for example, to upload files according with the GraphQL multipart request specification (see the existing middleware).

Let's look at an example with adding a user authorization header to each request that is stored in local storage.

import createRelayNetwork, {
  RelayNetworkMiddleware,
} from '@os-team/relay-network-creator';

const auth: RelayNetworkMiddleware = (next) => (req) => {
  const key = localStorage.getItem('key');
  if (key) {
    req.headers['Authorization'] = `Bearer ${key}`;
  }
  return next(req);
};

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  middlewares: [auth],
});

In some cases, it is necessary to modify a response or do some work with it. Let's create a middleware to log an error response.

const log: RelayNetworkMiddleware = (next) => async (req) => {
  const res = await next(req);
  const { errors } = res;
  if (errors) console.error(errors);
  return res;
};

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  middlewares: [log],
});

Let's look at another example. Most likely, your application has authorization. It would be a good idea to check every response coming from the GraphQL server for an authorization error.

If an authorization error was found, we will redirect the user to the login page. Thus, if your API deletes a user's session (for example, from Redis), the user will be redirected to the login page when he or she tries to make the next authorized request.

import createRelayNetwork, {
  RelayNetworkMiddleware,
} from '@os-team/relay-network-creator';
import { GraphQLResponseWithData } from 'relay-runtime';

const redirectUnauthorized: RelayNetworkMiddleware = (next) => async (req) => {
  const res = await next(req);
  const { errors } = res as GraphQLResponseWithData;
  if (errors && errors[0].code === 'unauthenticated') {
    window.location.href = '/signin/';
  }
  return res;
};

const network = createRelayNetwork({
  url: 'https://api.domain.com/graphql',
  middlewares: [redirectUnauthorized],
});