How to use apollo-link-context - 10 common examples

To help you get started, we’ve selected a few apollo-link-context examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Jordaneisenburger / fallback-studio / src / pwa-studio / packages / venia-concept / src / __tests__ / index.spec.js View on Github external
jest.isolateModules(() => {
        // Execute index.js.
        require('../');

        // Assert.
        expect(setContext).toHaveBeenCalled();
        const contextCallback = setContext.mock.calls[0][0];
        expect(
            contextCallback(null, { headers: { foo: 'bar' } })
        ).toMatchObject({
            headers: {
                foo: 'bar',
                authorization: ''
            }
        });

        // It includes the authorization header if the signin_token is present.
        getItem.mockReturnValueOnce('blarg');
        expect(contextCallback(null, { headers: {} })).toMatchObject({
            headers: {
                authorization: 'Bearer blarg'
            }
        });
github priley86 / how-to-graphql / frontend / utils / init-apollo.js View on Github external
let uri;
  if (isDevelopmentMode) {
    // set this back to localhost:4000 if using `now dev` to debug Next.js server side
    uri = isBrowser ? 'http://localhost:4000' : 'http://backend:4000'; // Server URL (Docker handles backend resolution automatically)
  } else {
    uri = apiHost;
  }

  const httpLink = new HttpLink({
    uri,
    credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
    // Use fetch() polyfill on the server
    fetch: !isBrowser && fetch
  });

  const authLink = setContext((_, { headers }) => {
    const token = getToken && getToken();
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : ''
      }
    };
  });

  return new ApolloClient({
    connectToDevTools: isBrowser,
    ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
    link: authLink.concat(httpLink),
    cache: new InMemoryCache().restore(initialState || {})
  });
}
github artsy / metaphysics / src / lib / stitching / exchange / link.ts View on Github external
// authenticated requests to Exchange.
      if (tokenLoader) {
        return tokenLoader().then(({ token }) => {
          return {
            headers: Object.assign(headers, {
              Authorization: `Bearer ${token}`,
            }),
          }
        })
      }
      // Exchange uses no authentication for now
      return { headers }
    }
  )

  const analyticsMiddleware = setContext(
    (_request, context: { headers: {}; graphqlContext: ResolverContext }) => {
      if (!context.graphqlContext) return context
      const userAgent = context.graphqlContext.userAgent
      const headers = {
        ...context.headers,
        "User-Agent": userAgent ? userAgent + "; Metaphysics" : "Metaphysics",
      }
      return { headers }
    }
  )

  return middlewareLink
    .concat(authMiddleware)
    .concat(analyticsMiddleware)
    .concat(responseLoggerLink("Exchange"))
    .concat(httpLink)
github mirumee / saleor / saleor / static / dashboard-next / index.tsx View on Github external
import SduiThemeProvider from "@ui/styles/ThemeProvider";

interface ResponseError extends ErrorResponse {
  networkError?: Error & {
    statusCode?: number;
    bodyText?: string;
  };
}

const invalidTokenLink = onError((error: ResponseError) => {
  if (error.networkError && error.networkError.statusCode === 401) {
    removeAuthToken();
  }
});

const authLink = setContext((_, context) => {
  const authToken = getAuthToken();
  return {
    ...context,
    headers: {
      ...context.headers,
      Authorization: authToken ? `JWT ${authToken}` : null
    }
  };
});

// DON'T TOUCH THIS
// These are separate clients and do not share configs between themselves
// so we need to explicitly set them
const linkOptions = {
  uri: API_URI
};
github demokratie-live / democracy-client / src / graphql / client.js View on Github external
default:
        return o._id;
    }
  },
});

const persistor = new CachePersistor({
  cache,
  storage: AsyncStorage,
  debug: false,
  debounce: 1000,
  // maxSize: false
});

const authLinkMiddleware = setContext(async (_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = await AsyncStorage.getItem('auth_token');
  const refreshToken = await AsyncStorage.getItem('auth_refreshToken');

  if (token && refreshToken) {
    const decodedToken = jwtDecode(token);
    const decodedRefreshToken = jwtDecode(refreshToken);

    const currentTime = Date.now() / 1000;
    if (decodedToken.exp >= currentTime || decodedRefreshToken.exp >= currentTime) {
      // Token valid
      return {
        headers: {
          ...headers,
          'x-token': token,
          'x-refresh-token': refreshToken,
github parkerziegler / github-search / App.js View on Github external
import { setContext } from 'apollo-link-context';
import { withClientState } from 'apollo-link-state';
import { ApolloProvider } from 'react-apollo';
import { Constants } from 'expo';

import { token } from './config';
import RootNavigator from './app/components/Navigation/RootNavigator';
import searchResolvers from './app/resolvers/searchResolvers';
import repositoryResolvers from './app/resolvers/repositoryResolvers';
import { merge } from 'lodash';

const httpLink = createHttpLink({
  uri: 'https://api.github.com/graphql',
});

const authLink = setContext((_, { headers }) => {
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    },
  };
});

const cache = new InMemoryCache();

const stateLink = withClientState({
  ...merge(searchResolvers, repositoryResolvers),
  cache,
});
github ooade / next-apollo-auth / lib / initApollo.js View on Github external
function create(initialState, { getToken }) {
	const httpLink = createHttpLink({
		uri: 'http://localhost:3000/graphql',
		credentials: 'same-origin'
	})

	const authLink = setContext((_, { headers }) => {
		const token = getToken()
		return {
			headers: {
				...headers,
				Cookie: token ? token : null
			}
		}
	})

	return new ApolloClient({
		connectToDevTools: process.browser,
		ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
		link: authLink.concat(httpLink),
		cache: new InMemoryCache().restore(initialState || {})
	})
}
github zeit / next.js / examples / with-apollo-auth / lib / apollo.js View on Github external
if (typeof window === 'undefined') {
    if (process.env.https_proxy) {
      fetchOptions.agent = new (require('https-proxy-agent'))(
        process.env.https_proxy
      )
    }
  }

  const httpLink = new HttpLink({
    uri: 'https://api.graph.cool/simple/v1/cj5geu3slxl7t0127y8sity9r', // Server URL (must be absolute)
    credentials: 'same-origin',
    fetch,
    fetchOptions,
  })

  const authLink = setContext((request, { headers }) => {
    const token = getToken()
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : '',
      },
    }
  })

  // Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
  return new ApolloClient({
    ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
    link: authLink.concat(httpLink),
    cache: new InMemoryCache().restore(initialState),
  })
}
github unwelch / unwel.ch / frontend / src / lib / create-apollo-client.js View on Github external
const createAuthLink = token => {
  return setContext((_, { headers }) => {
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : null
      }
    }
  })
}
github hasura / graphql-engine / community / sample-apps / whatsapp-clone-typescript-react / react-app / src / apollo-client.ts View on Github external
const httpLink = new HttpLink({
  uri: httpUri,
})

const wsLink = new WebSocketLink({
  uri: wsUri,
  options: {
    lazy: true,
    reconnect: true,
    connectionParams: () => {
      return { headers: {'Authorization': getAuthHeader()} };
    },
  },
})

const authLink = setContext((_, { headers }) => {
  const auth = getAuthHeader()

  return {
    headers: {
      ...headers,
      Authorization: auth,
    },
  }
})

const terminatingLink = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query) as OperationDefinitionNode
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,

apollo-link-context

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

MIT
Latest version published 4 years ago

Package Health Score

58 / 100
Full package analysis

Similar packages