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

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 opencollective / opencollective-frontend / src / lib / initClient.js View on Github external
if (error) {
          const { message, locations, path } = error;
          console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
          return;
        }

        console.error('[GraphQL error]: Received null error');
      });
    }

    if (networkError) {
      console.error(`[Network error]: ${networkError}`);
    }
  });

  const httpLink = new HttpLink({
    uri: getGraphqlUrl(),
    fetch,
  });

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

  return new ApolloClient({
    connectToDevTools: process.browser,
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    cache: cache.restore(initialState),
    link,
  });
}
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 zeit / next.js / examples / with-apollo / lib / apollo.js View on Github external
function createApolloClient(initialState = {}) {
  // 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: new HttpLink({
      uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch,
    }),
    cache: new InMemoryCache().restore(initialState),
  })
}
github ammezie / techies / src / main.js View on Github external
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
import App from './App'
import router from './router'

Vue.config.productionTip = false

// install the vue-momnet plugin
Vue.use(require('vue-moment'))

const httpLink = new HttpLink({ uri: 'http://localhost:4000/' })

const httpLinkAuth = setContext((_, { headers }) => {
  // get the authentication token from localstorage if it exists
  const token = localStorage.getItem('USER_TOKEN')

  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      Authorization: token ? `Bearer ${token}` : ''
    }
  }
})

// Create the apollo client
const apolloClient = new ApolloClient({
github OriginProtocol / origin / experimental / origin-graphql / src / links / schema.js View on Github external
const token = localStorage.getItem('growth_auth_token')
  const returnObject = {
    headers: {
      ...headers
    }
  }

  if (token) {
    returnObject.headers['authentication'] = `{"growth_auth_token": "${token}"}`
  }

  // return the headers to the context so httpLink can read them
  return returnObject
})

const httpLink = new HttpLink({ uri: `${growthServerAddress}/graphql`, fetch })

const schema = mergeSchemas({
  schemas: [
    makeRemoteExecutableSchema({
      schema: growthSchema,
      link: authLink.concat(httpLink)
    }),
    makeExecutableSchema({ typeDefs, resolvers })
  ]
})

export default schema
github graphql-boilerplates / node-graphql-server / index.ts View on Github external
async function run() {

  // Step 1: Create local version of the CRUD API
  const link = new HttpLink({ uri: process.env.GRAPHQL_ENDPOINT, fetch })
  const graphcoolSchema = makeRemoteExecutableSchema({
    schema: await introspectSchema(link),
    link,
  })

  // Step 2: Define schema for the new API
  const extendTypeDefs = `
    extend type Query {
      viewer: Viewer!
    }

    type Viewer {
      me: User
      topPosts(limit: Int): [Post!]!
    }
github qhacks / qhacks-dashboard / packages / client / ApolloClient.js View on Github external
clientName: CLIENT_NAME,
      clientVersion: CLIENT_VERSION
    };

    operation.setContext({
      http: {
        includeExtensions: true
      }
    });

    return forward(operation);
  });

  // Terminating link to fetch data from server
  // NOTE: Reads request headers from context
  const networkLink = new HttpLink({
    uri: GRAPHQL_ENDPOINT
  });

  const apolloClient = new ApolloClient({
    cache,
    link: ApolloLink.from([
      errorLink,
      stateLink,
      authLink,
      clientIdentifierLink,
      networkLink
    ])
  });

  return {
    apolloClient,
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

apollo-link-http

HTTP transport layer for GraphQL

MIT
Latest version published 4 years ago

Package Health Score

64 / 100
Full package analysis

Similar packages