Skip to content

Instantly share code, notes, and snippets.

@hmelenok
Created August 22, 2019 08:04
Show Gist options
  • Save hmelenok/360a56c0cf5631929c05ebb259f29ec3 to your computer and use it in GitHub Desktop.
Save hmelenok/360a56c0cf5631929c05ebb259f29ec3 to your computer and use it in GitHub Desktop.
import AWSAppSyncClient, {createAppSyncLink} from 'aws-appsync';
import {PureQueryOptions} from 'apollo-client';
import {MutationOptions, QueryOptions, ApolloQueryResult} from 'apollo-client';
import {map} from 'lodash';
import AppSyncConfig from '../../aws.config';
import {getAccessToken, getDefaultQueryParams, getMeteorTokenString} from '../helpers/apiHelper';
import {logError, logResponse} from './apolloLogHelpers';
import '../polyfills/server-fetch';
import {InMemoryCache} from 'apollo-cache-inmemory';
import {setContext} from 'apollo-link-context';
import {ApolloLink} from 'apollo-link';
import {createHttpLink} from 'apollo-link-http';
const credentials = {
url: AppSyncConfig.API_URL,
region: AppSyncConfig.REGION,
auth: {
type: AppSyncConfig.AUTHENTICATION_TYPE,
apiKey: AppSyncConfig.API_KEY
}
};
const httpLink = createAppSyncLink({
...credentials,
resultsFetcherLink: ApolloLink.from([
setContext((request, previousContext) => ({
headers: {
...previousContext.headers,
Authorization: getAccessToken() || getMeteorTokenString()
}
})),
createHttpLink({
uri: AppSyncConfig.API_URL
})
]),
complexObjectsCredentials: (): null => null
});
export const apolloClient = new AWSAppSyncClient(
{
...credentials,
disableOffline: true
},
{
link: httpLink,
cache: new InMemoryCache()
}
);
export const query = (options: QueryOptions): Promise<any> =>
apolloClient
.query({
...getDefaultQueryParams(),
fetchPolicy: 'network-only',
...options
})
.then((response: ApolloQueryResult<any>) => {
logResponse({response, options, type: 'query'});
return response.data || {};
})
.catch((error: Error) => {
logError({
error,
options,
type: 'query'
});
throw error;
});
export const mutate = (options: MutationOptions): Promise<any> => {
const defaultParams = getDefaultQueryParams();
return apolloClient
.mutate({
...defaultParams,
fetchPolicy: 'no-cache',
...options,
refetchQueries: map(options.refetchQueries, (query: PureQueryOptions) => ({
...query,
context: defaultParams.context
}))
})
.then(response => {
logResponse({response, options, type: 'mutation'});
return response.data || {};
})
.catch((error: Error) => {
logError({
error,
options,
type: 'mutation'
});
throw error;
});
};
export default apolloClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment