@cobuildlab/8base-chat
Version:
Chat component that uses 8base
88 lines (73 loc) • 2.2 kB
text/typescript
import { SubscriptionLink } from '@8base/apollo-links';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { ApolloLink, split } from 'apollo-link';
import { BatchHttpLink } from 'apollo-link-batch-http';
import { setContext } from 'apollo-link-context';
import { onError } from 'apollo-link-error';
import { HttpLink } from 'apollo-link-http';
import { getMainDefinition } from 'apollo-utilities';
import { log } from 'shared/utils';
import resolvers from './resolvers';
// -- TYPES
export interface ICreateApolloClientOptions {
uri: string;
token: string;
workspaceId: string;
}
// -- MAIN
function createApolloClient({ uri, token, workspaceId }: ICreateApolloClientOptions) {
const batchHttpLink = new BatchHttpLink({ uri });
const httpLink = new HttpLink({ uri });
const subscriptionLink = new SubscriptionLink({
uri: 'wss://ws.8base.com',
getAuthState: () => ({
token,
workspaceId,
}),
onAuthError: error => {
log('log', '[Subscription error]:', error);
},
});
const onErrorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
log(
'log',
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
}
if (networkError) {
log('log', '[Network error]:', networkError);
}
});
const authLink = setContext((_, { headers }) => ({
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
}));
const networkLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
subscriptionLink,
split(
operation => operation.getContext().important === true,
httpLink,
batchHttpLink,
),
);
const cache = new InMemoryCache();
return new ApolloClient({
link: ApolloLink.from([authLink, onErrorLink, networkLink]),
cache,
resolvers,
});
}
export default createApolloClient;