apollo-link-context#setContext JavaScript Examples

The following examples show how to use apollo-link-context#setContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: graphql.js    From mongodb-graphql-demo with Apache License 2.0 6 votes vote down vote up
initGraphQLClient = () => {
	hasLoggedInUser();
	if (!hasLoggedInUser()) {
		loginAnonymous();
	}

	if (hasLoggedInUser()) {
		const accessToken = getCurrentUser().auth.activeUserAuthInfo.accessToken;

		// Add an Authorization header to each GraphQL request
		const authLink = setContext((_, { headers }) => ({
			headers: {
				...headers,
				Authorization: `Bearer ${accessToken}`,
			},
		}));

		// Connect Apollo to the GraphQL Endpoint
		const GRAPHQL_URL = `https://stitch.mongodb.com/api/client/v2.0/app/${CONFIG.APP_ID}/graphql`;
		const httpLink = new HttpLink({ uri: GRAPHQL_URL });

		// Instantiate the Apollo Client
		const client = new ApolloClient({
			link: authLink.concat(httpLink),
			cache: new InMemoryCache(),
		});

		return client;
	}
}
Example #2
Source File: index.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
authLink = setContext((request, { headers }) => {
  const token = ElectronStore.get("apiToken") || null;
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
})
Example #3
Source File: apolloClient.js    From stack-underflow with MIT License 6 votes vote down vote up
authLink = setContext(() => {
  const loggedUser = storage.loadUser();

  return {
    headers: {
      authorization: loggedUser ? loggedUser.token : null,
    },
  };
})
Example #4
Source File: apollo-client.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
createApolloClient = (token) => {
    const httpLink = createHttpLink({
      uri: process.env.REACT_APP_GRAPHQL_ENDPOINT || config["REACT_APP_GRAPHQL_ENDPOINT"],
      options: {
        reconnect: true,
      },
    });

    const authLink = setContext((_, { headers }) => {
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          "X-Auth-Token": token,
        },
      };
    });

    return new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache()
    });
  }
Example #5
Source File: ApolloConfig.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
function createApolloClient(getIdTokenClaims) {
  const GRAPHQL_ENDPOINT = process.env.REACT_APP_GRAPHQL_ENDPOINT;

  if (getIdTokenClaims == null) {
    return new ApolloClient({
      uri: GRAPHQL_ENDPOINT,
      cache: new InMemoryCache(),
    });
  }

  const httpLink = createHttpLink({
    uri: GRAPHQL_ENDPOINT,
  });

  const authLink = setContext(async (request, {headers}) => {
    const idTokenClaims = await getIdTokenClaims();
    // return the header to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        'X-Auth-Token': idTokenClaims.__raw,
      },
    };
  });

  return new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
  });
}
Example #6
Source File: App.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
createApolloClient = token => {
  const httpLink = createHttpLink({
    uri: getSlashGraphQLEndpoint(),
    options: {
      reconnect: true,
    },
  });

  const authLink = setContext((request, { headers }) => {
    // return the header to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        "X-Auth-Token": token,
      },
    };
  });

  return new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
  });
}
Example #7
Source File: App.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
createApolloClient = token => {
  const httpLink = createHttpLink({
    uri: config.graphqlUrl,
    options: {
      reconnect: true,
    },
  });

  const authLink = setContext((_, { headers }) => {
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        "X-Auth-Token": token,
      },
    };
  });

  return new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
  });
}
Example #8
Source File: graphql.js    From lifebank with MIT License 6 votes vote down vote up
authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem('token')

  if (!token) {
    return {
      headers
    }
  }

  return {
    headers: {
      ...headers,
      Authorization: `Bearer ${token}`
    }
  }
})
Example #9
Source File: apolloClient.js    From web with MIT License 6 votes vote down vote up
authLink = setContext(async (_, { headers }) => {
  const token = process.browser
    ? window.localStorage.getItem('token')
    : undefined;

  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token || '',
    },
  };
})
Example #10
Source File: apollo.js    From youdidao-unmanned-shop with MIT License 6 votes vote down vote up
authLink = setContext(async (_, { headers }) => {
  const accessToken = localStorage.getItem('accessToken');

  const authorizationHeader = accessToken ? { authorization: `Bearer ${accessToken}` } : {};

  return {
    headers: {
      ...headers,
      ...authorizationHeader,
    },
  };
})
Example #11
Source File: auth.js    From React-Messenger-App with MIT License 5 votes vote down vote up
function create(initialState, { getToken }) {
  const httpLink = createHttpLink({
    uri: "http://localhost:4000"
    //credentials: "same-origin"
  });

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

  let link = authLink.concat(httpLink);

  if (process.browser) {
    const token = getToken();
    const wsLink = new WebSocketLink({
      uri: `ws://localhost:4000`,
      options: {
        reconnect: true,
        connectionParams: {
          Authorization: `Bearer ${token}`
        }
      }
    });

    link = split(
      // split based on operation type
      ({ query }) => {
        const { kind, operation } = getMainDefinition(query);
        return kind === "OperationDefinition" && operation === "subscription";
      },
      wsLink,
      authLink.concat(httpLink)
    );
  }

  // Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
  return new ApolloClient({
    connectToDevTools: process.browser,
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    link,
    cache: new InMemoryCache().restore(initialState || {})
  });
}
Example #12
Source File: apollo.js    From saasgear with MIT License 5 votes vote down vote up
authLink = setContext((_, { headers }) => ({
  headers
}))
Example #13
Source File: ApolloProvider.js    From 0.4.1-Quarantime with MIT License 5 votes vote down vote up
authLink = setContext(() => {
  const token = localStorage.getItem('jwtToken');
  return {
    headers: {
      Authorization: token ? `Bearer ${token}` : ''
    }
  };
})
Example #14
Source File: App.js    From web-frontend with MIT License 5 votes vote down vote up
function App() {
  const [token, setToken] = useState(null);

  const onAuthenticate = (token) => {
    setToken(token);
  };

  if (!token)
    return (
      <div>
        <input id="token" placeholder="github token" />
        <button
          onClick={() => onAuthenticate(document.getElementById("token").value)}
        >
          Authenticate
        </button>
      </div>
    );
  else {
    const httpLink = createHttpLink({
      uri: "https://api.github.com/graphql",
    });

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

    const client = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    });

    return (
      <ApolloProvider client={client}>
        <div className="App">
          <GitHubQuery />
        </div>
      </ApolloProvider>
    );
  }
}