Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

apollo-link-context

apollographql1.4mMIT1.0.20TypeScript support: included

An easy way to set and cache context changes for Apollo Link

readme


title: apollo-link-context

The setContext function takes a function that returns either an object or a promise that returns an object to set the new context of a request.

It receives two arguments: the GraphQL request being executed, and the previous context. This link makes it easy to perform async look up of things like authentication tokens and more!

import { setContext } from "apollo-link-context";

const setAuthorizationLink = setContext((request, previousContext) => ({
  headers: {authorization: "1234"}
}));

const asyncAuthLink = setContext(
  request =>
    new Promise((success, fail) => {
      // do some async lookup here
      setTimeout(() => {
        success({ token: "async found token" });
      }, 10);
    })
);

Caching lookups

Typically async actions can be expensive and may not need to be called for every request, especially when a lot of request are happening at once. You can setup your own caching and invalidation outside of the link to make it faster but still flexible!

Take for example a user auth token being found, cached, then removed on a 401 response:

import { setContext } from "apollo-link-context";
import { onError } from "apollo-link-error";

// cached storage for the user token
let token;
const withToken = setContext(() => {
  // if you have a cached value, return it immediately
  if (token) return { token };

  return AsyncTokenLookup().then(userToken => {
    token = userToken;
    return { token };
  });
});

const resetToken = onError(({ networkError }) => {
  if (networkError && networkError.name ==='ServerError' && networkError.statusCode === 401) {
    // remove cached token on 401 from the server
    token = null;
  }
});

const authFlowLink = withToken.concat(resetToken);

changelog

Change log


NOTE: This changelog is no longer maintained. Changes are now tracked in the top level CHANGELOG.md.


1.0.10

  • No changes

1.0.9

  • Added graphql 14 to peer and dev deps; Updated @types/graphql to 14
    @hwillson in #789

1.0.7

  • Update apollo-link #559

1.0.6

  • udate apollo link with zen-observable-ts PR#515

1.0.5

  • ApolloLink upgrade

1.0.4

  • ApolloLink upgrade

1.0.3

  • update rollup build

1.0.2

  • changed peer-dependency of apollo-link to actual dependency

1.0.1

  • moved to better rollup build

1.0.0

  • bump to major to signal API stability

0.1.0

  • initial release