How to use the apollo-link-http.createHttpLink function in apollo-link-http

To help you get started, we’ve selected a few apollo-link-http 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 letterpad / letterpad / client / serverRendering.js View on Github external
const { GET_OPTIONS } = require("../shared/queries/Queries");

// handle errors whie fetching data in the server.
const errorLink = onError(({ networkError, graphQLErrors }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
  }
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const httpLink = createHttpLink({
  uri: config.apiUrl,
  fetch,
});

const link = ApolloLink.from([errorLink, httpLink]);

module.exports.init = app => {
  app.get("*", (req, res, next) => {
    if (req.url === "/graphql") return next();
    // using the apolloclient we can fetch data from the backend
    const client = new ApolloClient({
      ssrMode: true,
      link: link,
      cache: new InMemoryCache(),
    });
github srtucker22 / chatty / client / src / app.js View on Github external
const store = createStore(
  reducer,
  {}, // initial state
  composeWithDevTools(
    applyMiddleware(thunk, navigationMiddleware),
  ),
);

// persistent storage
const persistor = persistStore(store);

const cache = new ReduxCache({ store });

const reduxLink = new ReduxLink(store);

const httpLink = createHttpLink({ uri: `http://${URL}` });

// middleware for requests
const middlewareLink = setContext((req, previousContext) => {
  // get the authentication token from local storage if it exists
  const { jwt } = store.getState().auth;
  if (jwt) {
    return {
      headers: {
        authorization: `Bearer ${jwt}`,
      },
    };
  }

  return previousContext;
});
github cleverbeagle / pup / startup / server / ssr.js View on Github external
onPageLoad(async (sink) => {
  if (checkIfBlacklisted(sink.request.url.path)) {
    sink.appendToBody(`
      
    `);

    return;
  }

  const apolloClient = new ApolloClient({
    ssrMode: true,
    link: createHttpLink({
      uri: Meteor.settings.public.graphQL.httpUri,
    }),
    cache: new InMemoryCache(),
  });

  const stylesheet = new ServerStyleSheet();
  const app = stylesheet.collectStyles(
    
      
        
      
    ,
  );

  // NOTE: renderToStringWithData pre-fetches all queries in the component tree. This allows the data
  // from our GraphQL queries to be ready at render time.
github zeit / next.js / examples / with-apollo-auth / lib / initApollo.js View on Github external
function create (initialState, { getToken, fetchOptions }) {
  const httpLink = createHttpLink({
    uri: 'https://api.graph.cool/simple/v1/cj5geu3slxl7t0127y8sity9r',
    credentials: 'same-origin',
    fetchOptions
  })

  const authLink = setContext((_, { 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
github artsy / metaphysics / src / lib / stitching / exchange / link.ts View on Github external
export const createExchangeLink = () => {
  const httpLink = createHttpLink({
    fetch,
    uri: urljoin(EXCHANGE_API_BASE, "graphql"),
  })

  const authMiddleware = setContext(
    (_request, { graphqlContext }: { graphqlContext: ResolverContext }) => {
      const tokenLoader = graphqlContext && graphqlContext.exchangeTokenLoader
      const headers = {
        ...(graphqlContext && requestIDHeaders(graphqlContext.requestIDs)),
      }
      // If a token loader exists for Exchange (i.e. this is an authenticated request), use that token to make
      // authenticated requests to Exchange.
      if (tokenLoader) {
        return tokenLoader().then(({ token }) => {
          return {
            headers: Object.assign(headers, {
github pact-foundation / pact-js / examples / graphql / consumer.ts View on Github external
import { ApolloClient, HttpLink } from "apollo-boost";
import { InMemoryCache } from "apollo-cache-inmemory";
import gql from "graphql-tag";
import { createHttpLink } from "apollo-link-http";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: createHttpLink({
    fetch: require("node-fetch"),
    headers: {
      foo: "bar",
    },
    uri: "http://localhost:4000/graphql",
  }),
});

export function query(): any {
  return client
    .query({
      query: gql`
        {
          hello
        }
      `,
github realm / realm-graphql / src / client.ts View on Github external
private constructor(config: ClientConfig, accessToken: string) {
    const endpoint = new URI(config.user.server).segmentCoded(['graphql', config.realmPath]);

    const httpLink = createHttpLink({
      uri: endpoint.toString(),
      fetch: AuthenticationHelper.getFetch()
    });

    const authLink = setContext((_, { headers }) => {
      return {
        headers: {
          ...headers,
          authorization: this.accessToken ? this.accessToken : null,
        }
      };
    });

    let subscriptionScheme: string;
    switch (endpoint.scheme()) {
      case 'http':
github connect-foundation / 2019-21 / frontend / host-app / src / libs / createApolloClient.js View on Github external
export default function createApolloClient(uri, token) {
	const httpLink = createHttpLink({ uri });
	if (token) {
		const authLink = setContext((_, { headers }) => {
			return {
				headers: {
					...headers,
					authorization: `Bearer ${token}`,
				},
			};
		});

		return new ApolloClient({
			link: authLink.concat(httpLink),
			cache: new InMemoryCache(),
		});
	} else {
		return new ApolloClient({
github prisma-labs / graphql-yoga / examples / fullstack-vue / frontend / src / main.js View on Github external
import Vue from 'vue';
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import VueApollo from 'vue-apollo';
import App from './App.vue';
import router from './router';
import store from './store';

const link = createHttpLink({
  uri: 'http://localhost:4000',
});

const apolloClient = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true,
});


Vue.use(VueApollo);

Vue.config.productionTip = false;

const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
github arojunior / awesome-feed / src / services / apolloClient.js View on Github external
import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import store from '../modules/index';
import { GITHUB_GRAPHQL } from '../constants';

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

const authLink = setContext((_, { headers }) => ({
  headers: {
    ...headers,
    authorization: `Basic ${store.getState().Login.token}`,
  },
}));

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

export default client;

apollo-link-http

HTTP transport layer for GraphQL

MIT
Latest version published 5 years ago

Package Health Score

64 / 100
Full package analysis

Similar packages