How to use the apollo-link.ApolloLink function in apollo-link

To help you get started, we’ve selected a few apollo-link 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 okgrow / advanced-graphql / web / src / client.js View on Github external
import { BrowserRouter } from 'react-router-dom';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { HttpLink } from 'apollo-link-http';
import WsLink from 'apollo-link-ws';
import Cache from 'apollo-cache-inmemory';
import App from './components/App';

const errorLink = onError(({ graphqlErrors, networkError }) => {
  // could also be sent to an error logger
  console.error('Apollo Errors caught!', { graphqlErrors, networkError });
});

const authLink = new ApolloLink((operation, forward) => {
  const token = localStorage.getItem('AUTH_TOKEN');

  operation.setContext(() => ({
    headers: {
      authorization: token ? `JWT ${token}` : null,
    },
  }));

  return forward(operation);
});

const hasSubscriptionOperation = operation =>
  operation.query.definitions.reduce(
    (result, definition) => result || definition.operation === 'subscription',
    false
  );
github CharlyJazz / GraphQL-Medium-Clone / client / src / index.js View on Github external
import { withClientState } from 'apollo-link-state'

import { ApolloLink } from 'apollo-link'

import { BrowserRouter } from 'react-router-dom'

import registerServiceWorker from './registerServiceWorker'

import initialState from './apollo/initialState'

// Here you create the HttpLink that will connect your ApolloClient
// instance with the GraphQL API; your GraphQL server will be running
// on http://localhost:3000.
const httpLink = new HttpLink({ uri: 'http://localhost:3000/graphql' })
// Add the authorization to the headers
const JWTMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      Authorization: localStorage.getItem('Authorization') || null,
    }
  })

  return forward(operation)
})
// This is the same cache you pass into new ApolloClient
const cache = new InMemoryCache()
// Create state Link
const stateLink = withClientState({
  cache,
  resolvers: {
    Mutation: {
      setCurrentUser: (_, { id, token, username, picture }, { cache }) => {
github danielniquet / instagram-clone / instagram-clone-client / src / apollo.js View on Github external
import { ApolloClient } from 'apollo-client';
// import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloLink } from 'apollo-link';
import { createUploadLink } from 'apollo-upload-client'

const httpLink = createUploadLink({uri:'http://localhost:3000/graphql'})

const authMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      "x-token": localStorage.getItem('token') || null,
    }
  });
  return forward(operation);
})


const authAfterware = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    const context = operation.getContext();
    const { response: { headers } } = context;
    if (headers) {
      const token = headers.get("x-token");
github arkhn / pyrog / client-v2 / src / app.tsx View on Github external
const persistedReducer = persistReducer(persistConfig, mainReducer)

const finalCreateStore = applyMiddleware(...middlewares)(createStore);
const store = finalCreateStore(persistedReducer);

let persistor = persistStore(store)

// APOLLO

// HttpLink
const httpLink = new HttpLink({
  uri: process.env.HTTP_BACKEND_URL,
  fetch: fetch
});

const middlewareLink = new ApolloLink((operation, forward) => {
  const token = localStorage.getItem(process.env.AUTH_TOKEN);

  operation.setContext({
    headers: {
      Authorization: token ? `Bearer ${token}` : ""
    }
  });

  return forward(operation);
});

const httpLinkAuth = middlewareLink.concat(httpLink);

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
github danielmahon / opencrud-admin / src / providers / ApolloProvider.js View on Github external
constructor(props) {
    super(props);

    const httpLink = new HttpLink({
      uri: process.env.REACT_APP_GRAPHQL_ENDPOINT,
    });

    // const cache = new InMemoryCache({ dataIdFromObject: o => o.id });
    const cache = new InMemoryCache();

    const middlewareLink = new ApolloLink((operation, forward) => {
      // get the authentication token from props if it exists
      // return the headers to the context so httpLink can read them
      const { headers = {} } = operation.getContext();
      operation.setContext({
        headers: {
          Authorization: `Bearer ${props.getToken()}`,
          ...headers,
        },
      });
      return forward(operation);
    });

    // authenticated httplink
    const httpLinkAuth = middlewareLink.concat(httpLink);

    const errorLink = onError(({ graphQLErrors, networkError }) => {
github apollographql / apollo-link-state / packages / apollo-link-state / src / __tests__ / index.ts View on Github external
it('runs resolvers for missing client queries with server data', done => {
  const query = gql`
    query Mixed {
      foo @client {
        bar
      }
      bar {
        baz
      }
    }
  `;
  const sample = new ApolloLink(() =>
    Observable.of({ data: { bar: { baz: true } } }),
  );
  const client = withClientState({ resolvers });
  execute(client.concat(sample), { query }).subscribe(({ data }) => {
    try {
      expect(data).toEqual({ foo: { bar: true }, bar: { baz: true } });
    } catch (error) {
      done.fail(error);
    }
    done();
  }, done.fail);
});
github dvtng / graphql-automock / src / mock-apollo-client.js View on Github external
export const mockApolloClient = params => {
  const mockedSchema = mockSchema(params);

  const schemaLink = new ApolloLink(operation => {
    return new Observable(observer => {
      graphql(
        mockedSchema,
        print(operation.query),
        operation.getContext,
        operation.variables
      ).then(result => {
        observer.next(result);
        observer.complete();
      });
    });
  });

  const mockedClient = new ApolloClient({
    link: params.controller
      ? controllerLink(params.controller).concat(schemaLink)
github apollographql / apollo-link / packages / apollo-link-error / src / index.ts View on Github external
export function onError(errorHandler: ErrorHandler): ApolloLink {
  return new ApolloLink((operation, forward) => {
    return new Observable(observer => {
      let sub;
      let retriedSub;
      let retriedResult;

      try {
        sub = forward(operation).subscribe({
          next: result => {
            if (result.errors) {
              retriedResult = errorHandler({
                graphQLErrors: result.errors,
                response: result,
                operation,
                forward,
              });
github awslabs / aws-mobile-appsync-sdk-js / packages / aws-appsync / src / link / complex-object-link.ts View on Github external
export const complexObjectLink = (credentials) => {
    return new ApolloLink((operation, forward) => {
        return new Observable(observer => {
            let handle;

            const { operation: operationType } = getOperationDefinition(operation.query);
            const isMutation = operationType === 'mutation';
            const objectsToUpload = isMutation ? findInObject(operation.variables) : {};

            let uploadPromise = Promise.resolve(operation);

            if (Object.keys(objectsToUpload).length) {
                const uploadCredentials = typeof credentials === 'function' ? credentials.call() : credentials;

                uploadPromise = Promise.resolve(uploadCredentials)
                    .then(credentials => {
                        const uploadPromises = Object.entries(objectsToUpload).map(([_, fileField]) => upload(fileField, { credentials }));
github MerlinLabs / moleculer-graphql / src / Gateway / MoleculerLink.js View on Github external
function createMoleculerLink(opts: ServiceOptions): ApolloLink {
  return new ApolloLink(
    operation =>
      new Observable(observer => {
        const { credentials, fetcherOptions } = operation.getContext();
        const { operationName, extensions, variables, query } = operation;
        const { broker, service } = opts;

        broker.call(`${service}.graphql`, {
          credentials,
          query: print(query),
          variables,
          extensions,
          operationName
        })
          .then(result => {
            observer.next(result);
            observer.complete();