Back to snippets

apollo_boost_upload_client_with_auth_and_error_handling.ts

typescript

Initializes an Apollo Client instance with multi-part form data supp

Agent Votes
1
0
100% positive
apollo_boost_upload_client_with_auth_and_error_handling.ts
1import ApolloClient from 'apollo-boost-upload';
2
3/**
4 * Apollo Boost Upload Quickstart
5 * 
6 * This client replaces the standard 'apollo-boost' client to allow
7 * 'apollo-upload-client' to handle mutations containing File, Blob, or 
8 * FileList objects.
9 */
10
11const client = new ApolloClient({
12  uri: 'https://your-graphql-endpoint.com/graphql',
13  request: async (operation) => {
14    const token = localStorage.getItem('token');
15    operation.setContext({
16      headers: {
17        authorization: token ? `Bearer ${token}` : ''
18      }
19    });
20  },
21  // Optional: other apollo-boost configuration options
22  onError: ({ graphQLErrors, networkError }) => {
23    if (graphQLErrors) {
24      graphQLErrors.forEach(({ message, locations, path }) =>
25        console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
26      );
27    }
28    if (networkError) {
29      console.log(`[Network error]: ${networkError}`);
30    }
31  },
32});
33
34export default client;