@tokens-studio/sdk
Version:
The official SDK for Tokens Studio
73 lines • 3 kB
JavaScript
import { ApolloClient, from, HttpLink, split, } from '@apollo/client/core/index.js';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions/index.js';
import { createClient } from 'graphql-ws';
import { getMainDefinition } from '@apollo/client/utilities/index.js';
import { removeTypenameFromVariables } from '@apollo/client/link/remove-typename/index.js';
import { setContext } from '@apollo/client/link/context/index.js';
import { VoidCache } from './cache.js';
/**
* Creates an instance of the SDK Client
*
* The webSocketImpl parameter is used to inject a custom WebSocket implementation. This is useful for testing purposes, and handling isomorphic environments.
* @returns
*/
export function create({ auth, host = 'graphql.app.tokens.studio', secure = true, fetch, cookies, webSocketImpl, }) {
const authLink = setContext((_, { headers }) => {
// return the headers to the context so httpLink can read them
/* v8 ignore next */
const cookieHeader = cookies
?.map((cookie) => `${cookie.name}=${cookie.value}`)
.join('; ');
const requestHeaders = {
...headers,
// dont need to cover auth fallback or cookies
/* v8 ignore next 2 */
...(auth ? { authorization: auth } : {}),
...(cookieHeader ? { Cookie: cookieHeader } : {}),
};
return {
headers: requestHeaders,
};
});
const removeTypenameLink = removeTypenameFromVariables();
const httpLink = new HttpLink({
// in testing, we always use localhost http and never https, so we dont cover this branch
/* v8 ignore next */
uri: `http${secure ? 's' : ''}://${host}/graphql`,
credentials: 'include',
fetch,
});
const wsLink = new GraphQLWsLink(createClient({
webSocketImpl,
/* v8 ignore next */
url: `ws${secure ? 's' : ''}://${host}/subscriptions`,
connectionParams: {
authToken: auth,
},
}));
// The split function takes three parameters:
//
// * A function that's called for each operation to execute
// * The Link to use for an operation if the function returns a "truthy" value
// * The Link to use for an operation if the function returns a "falsy" value
const splitLink = split(({ query }) => {
const definition = getMainDefinition(query);
return (definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription');
}, wsLink, httpLink);
return new ApolloClient({
link: from([removeTypenameLink, authLink, splitLink]),
cache: new VoidCache(),
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
},
});
}
//# sourceMappingURL=graphql.js.map