Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-upload-client' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
);
// 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
);
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"
})
});
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: {
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
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}`;
}
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
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}`;
}
}
]
}
}
});
// 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
},
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
}
}
export default uri =>
ApolloLink.split(
({ variables }) => extractFiles(cloneDeep(variables)).length > 0,
createUploadLink({ uri, credentials: 'include' }),
new BatchHttpLink({
uri,
credentials: 'include'
})
);