How to use apollo-upload-client - 10 common examples

To help you get started, we’ve selected a few apollo-upload-client 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 withspectrum / spectrum / shared / graphql / index.js View on Github external
);

      // Retry mutations for a looong time, those are very important to us so we want them to go through eventually
      if (isMutation) {
        return !!error && count < 25;
      }

      // Retry queries for way less long as this just ends up showing
      // loading indicators for that whole time which is v annoying
      return !!error && count < 6;
    },
  });

  // HTTP Link for queries and mutations including file uploads
  const httpLink = retryLink.concat(
    createUploadLink({
      uri: API_URI,
      credentials: 'include',
      headers,
    })
  );

  // Switch between the two links based on operation
  const link = split(
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return kind === 'OperationDefinition' && operation === 'subscription';
    },
    wsLink,
    httpLink
  );
github ahrbil / TDI-Exchange / packages / web / src / apolloClient.js View on Github external
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { createUploadLink } from "apollo-upload-client";

import { GQL_URI } from "./constants";

const cache = new InMemoryCache();

export const apolloClient = new ApolloClient({
  cache,
  // createUploadLink handles the file upload
  link: createUploadLink({
    uri: GQL_URI,
    credentials: "include"
  })
});
github Akryum / vue-cli-plugin-apollo / graphql-client / src / index.js View on Github external
typeDefs = undefined,
  // Local Resolvers
  resolvers = undefined,
  // Hook called when you should write local state in the cache
  onCacheInit = undefined,
}) {
  let wsClient, authLink, stateLink
  const disableHttp = websocketsOnly && !ssr && wsEndpoint

  // Apollo cache
  if (!cache) {
    cache = new InMemoryCache(inMemoryCacheOptions)
  }

  if (!disableHttp) {
    const httpLink = createUploadLink({
      uri: httpEndpoint,
      ...httpLinkOptions,
    })

    if (!link) {
      link = httpLink
    } else if (defaultHttpLink) {
      link = from([link, httpLink])
    }

    // HTTP Auth header injection
    authLink = setContext((_, { headers }) => {
      const authorization = getAuth(tokenName)
      const authorizationHeader = authorization ? { authorization } : {}
      return {
        headers: {
github DimiMikadze / create-social-network / frontend / src / utils / apollo-client.js View on Github external
export const createApolloClient = (apiUrl, websocketApiUrl) => {
  const cache = new InMemoryCache();

  const errorLink = handleErrors();
  const authLink = createAuthLink();
  const uploadLink = createUploadLink({ uri: apiUrl }); // Upload link also creates an HTTP link

  // Create WebSocket link
  const authToken = localStorage.getItem('token');
  const wsLink = new WebSocketLink({
    uri: websocketApiUrl,
    options: {
      timeout: 60000,
      reconnect: true,
      connectionParams: {
        authorization: authToken,
      },
    },
  });

  // Temporary fix for early websocket closure resulting in websocket connections not being instantiated
  // https://github.com/apollographql/subscriptions-transport-ws/issues/377
github strues / boldr / src / core / entry / client.js View on Github external
import App from '../App';

// Async font loading
WebFontLoader.load({
  google: {
    families: ['Roboto:300,600', 'Chivo:400,600'],
  },
});

const MOUNT_POINT = document.getElementById('app');
// Load the JWT if it exists.
// Get token will return null if it does not exist
const token = getToken();

// Apollo network interface
const networkInterface = createBatchingNetworkInterface({
  uri: process.env.BOLDR_GRAPHQL_URL,
  batchInterval: 10,
});
networkInterface.use([
  {
    applyBatchMiddleware(req, next) {
      // If headers don't exist for some reason
      // create them.
      if (!req.options.headers) {
        req.options.headers = {};
      }

      // Add our auth token to the headers
      // Authorization: 'Bearer Token'
      if (token) {
        req.options.headers.authorization = `Bearer ${token}`;
github strues / boldr / src / core / createApolloClient.js View on Github external
}
    params.ssrForceFetchDelay = 100;
    params.connectToDevTools = true;
  } else {
    params.ssrMode = true;
  }

  return new ApolloClient(params);
};

// Load the JWT if it exists.
// Get token will return null if it does not exist
const token = getToken();

// Apollo network interface
const networkInterface = createBatchingNetworkInterface({
  uri: process.env.GRAPHQL_ENDPOINT,
  batchInterval: 10,
});

networkInterface.use([
  {
    applyBatchMiddleware(req, next) {
      // If headers don't exist for some reason create them.
      if (!req.options.headers) {
        req.options.headers = {};
      }
      if (!process.browser) {
        req.options.headers.credentials = 'same-origin';
        req.options.headers.credentials = req.headers;
      }
      // Add our auth token to the headers
github srtucker22 / chatty / client / src / app.js View on Github external
import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws';
import { persistStore, autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
import _ from 'lodash';
import { WillPresentNotificationResult } from 'react-native-fcm';
import { NavigationActions } from 'react-navigation';
import { createBatchingNetworkInterface } from 'apollo-upload-client';

import AppWithNavigationState, { navigationReducer } from './navigation';
import auth from './reducers/auth.reducer';
import { logout } from './actions/auth.actions';
import { FirebaseClient } from './firebase-client';

const URL = 'localhost:8080'; // set your comp's url here

const networkInterface = createBatchingNetworkInterface({
  uri: `http://${URL}/graphql`,
  batchInterval: 10,
  queryDeduplication: true,
});

// middleware for requests
networkInterface.use([{
  applyBatchMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};
    }
    // get the authentication token from local storage if it exists
    const jwt = store.getState().auth.jwt;
    if (jwt) {
      req.options.headers.authorization = `Bearer ${jwt}`;
    }
github assembl / assembl / assembl / static2 / js / app / client.js View on Github external
}
      ]
    }
  }
});

// The object id retrieved is already unique, it's actually
// ObjectType:primaryKey encoded in base64, so we define our
// own dataIdFromObject instead of using the default one `${o.__typename}:o.id`.
// This allows us to define a custom resolver for the node query.
// for more info about customResolvers, read
// http://dev.apollodata.com/react/query-splitting.html

const dataIdFromObject = o => o.id;

const networkInterface = createNetworkInterface({
  uri: getFullPath('graphql', { slug: getDiscussionSlug() }),
  opts: {
    credentials: 'same-origin'
  }
});

// trace every graphql operation in sentry
networkInterface.use([
  {
    applyMiddleware: function (req, next) {
      Sentry.addBreadcrumb({
        category: 'graphql',
        message: `GraphQL operation: ${req.request.operationName}`,
        data: {
          variables: req.request.variables
        },
github polo13999 / airWatch / client / src / lib / initApollo.js View on Github external
function create(initialState, { getToken }) {
  let httpLink = createUploadLink({
    uri: `${envs.serverURL()}/graphql`,
    credentials: 'include'
  })
  const authLink = setContext((operation, inData) => {
    const { headers } = inData
    const token = getToken()
    console.log('token', token)
    console.log('operation', operation)
    if (token) {
      return operation[
        {
          headers: {
            ...headers,
            Cookie: token ? token : null
          }
        }
github sysgears / apollo-universal-starter-kit / modules / upload / client-react / netLink.js View on Github external
export default uri =>
  ApolloLink.split(
    ({ variables }) => extractFiles(cloneDeep(variables)).length > 0,
    createUploadLink({ uri, credentials: 'include' }),
    new BatchHttpLink({
      uri,
      credentials: 'include'
    })
  );

apollo-upload-client

A terminating Apollo Link for Apollo Client that fetches a GraphQL multipart request if the GraphQL variables contain files (by default FileList, File, or Blob instances), or else fetches a regular GraphQL POST or GET request (depending on the config and

MIT
Latest version published 6 months ago

Package Health Score

76 / 100
Full package analysis