Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "apollo-link-context in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-link-context' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

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'
            }
        });
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 || {})
  });
}
// 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)
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
};
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,
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,
});
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 || {})
	})
}
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),
  })
}
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
      }
    }
  })
}
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,

Is your System Free of Underlying Vulnerabilities?
Find Out Now