@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
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:
- @os-team/relay-network-mw-app-user-agent - to include more detailed app's user agent in each request made from React Native.
- @os-team/relay-network-mw-upload - to transform each request by GraphQL multipart request specification for file uploads.
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
andmethod
for example, to make specific requests to another API.headers
for example, to add a user authorization key to requests.timeout
andtimeoutMessage
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],
});