Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
UNSAFE_componentWillMount() {
const { protocol, host } = location;
const wsProtocol = protocol.includes('https') ? 'wss:' : 'ws:';
try {
const [, JWT] = (location.search || 'jwt=')
.match(/jwt=((?!&).)*/gi)[0]
.split('=');
localStorage.setItem('token', JWT);
const httpLink = ApolloLink.from([
AuthLink,
new BatchHttpLink({ uri: `${protocol}//${host}/graphql` }),
]);
const wsLink = new WebSocketLink({
uri: `${wsProtocol}//${host}/subscriptions`,
options: {
reconnect: true,
connectionParams: { JWT },
},
});
const link = split(
// split based on operation type
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink,
link = ApolloLink.split(
({ query, operationName }) => {
if (operationName.endsWith('_WS')) {
return true;
} else {
const operationAST = getOperationAST(query as any, operationName);
return !!operationAST && operationAST.operation === 'subscription';
}
},
wsLink,
new HttpLink({
uri: PUBLIC_SETTINGS.GRAPHQL_URL,
}),
);
} else {
link = new BatchHttpLink({ uri: PUBLIC_SETTINGS.LOCAL_GRAPHQL_URL });
}
const links = [errorLink, ...modules.link, /** ...modules.errorLink, */ link];
// Add apollo logger during development only
if ((process.env.NODE_ENV === 'development' || __DEBUGGING__) && __CLIENT__) {
links.unshift(apolloLogger);
}
let _apolloClient: ApolloClient;
const createApolloClient = () => {
if (_apolloClient) {
// return quickly if client is already created.
return _apolloClient;
}
const params: ApolloClientOptions = {
}
}
),
{
reset: () => {
// On apolloClient.resetStore() reset only netCache and keep localCache intact
return netCache.reset();
}
}
);
const getApolloClient = (): ApolloClient => client;
const queryLink = createNetLink
? createNetLink(apiUrl, getApolloClient)
: new BatchHttpLink({
uri: apiUrl,
credentials: 'include',
fetch
});
let apiLink = queryLink;
if (apiUrl && (__TEST__ || typeof navigator !== 'undefined')) {
const finalConnectionParams = {};
if (connectionParams) {
for (const connectionParam of connectionParams) {
Object.assign(finalConnectionParams, (connectionParam as any)());
}
}
const wsUri = apiUrl.replace(/^http/, 'ws');
}
}
),
{
reset: () => {
// On apolloClient.resetStore() reset only netCache and keep localCache intact
return netCache.reset();
}
}
);
const getApolloClient = (): ApolloClient => client;
const queryLink = createNetLink
? createNetLink(apiUrl, getApolloClient)
: new BatchHttpLink({
uri: apiUrl,
credentials: 'include',
fetch
});
let apiLink = queryLink;
if (apiUrl && (__TEST__ || typeof navigator !== 'undefined')) {
const finalConnectionParams = {};
if (connectionParams) {
for (const connectionParam of connectionParams) {
Object.assign(finalConnectionParams, (connectionParam as any)());
}
}
const wsUri = apiUrl.replace(/^http/, 'ws');
const makeHttpLink = urlParams => {
const host = graphqlHost(urlParams)
const uri = host
// We create a createPersistedQueryLink to lower network usage.
// With this, a prefetch is done using a hash of the query.
// if the server recognises the hash, it will reply with the full response.
return createPersistedQueryLink().concat(
new BatchHttpLink({
uri
}),
new RetryLink()
)
}
export default function(endpoint, ssr, initialCacheState) {
/* HTTP link selection: default to batched + APQ */
const link = createPersistedQueryLink().concat(
new BatchHttpLink({ uri: endpoint, credentials: 'include' })
);
// basic HTTP link
// const link = createHttpLink({ uri: endpoint, credentials: 'include' });
const cache = new InMemoryCache({
fragmentMatcher: new IntrospectionFragmentMatcher({
introspectionQueryResultData,
}),
});
return new ApolloClient({
ssrMode: ssr,
ssrForceFetchDelay: 100,
link,
cache: cache.restore(initialCacheState),
});
export default function(endpoint, ssr, initialCacheState) {
/* HTTP link selection: default to batched + APQ */
const link = createPersistedQueryLink().concat(
new BatchHttpLink({ uri: endpoint, credentials: 'include' })
);
const cache = new InMemoryCache({
fragmentMatcher: new IntrospectionFragmentMatcher({
introspectionQueryResultData,
}),
});
return new ApolloClient({
ssrMode: ssr,
ssrForceFetchDelay: 100,
link,
cache: cache.restore(initialCacheState),
});
}
export default function(endpoint, ssr, initialCacheState) {
/*
QUERY LINK SELECTION
A link is transport which GraphQL queries are pushed across.
You have many choices; see BasicGraphQLClientFactory for more details
*/
// Generally speaking this APQ + batching link is the right choice for most cases.
const automaticPersistHttp = createPersistedQueryLink().concat(
new BatchHttpLink({ uri: endpoint, credentials: 'include' })
);
/* HTTP link selection */
let link = automaticPersistHttp;
/*
SUBSCRIPTIONS LINK
Subscriptions are real-time data; they run over WebSockets.
When server-side rendering, we do not want to enable subscriptions so we don't link them;
enabling them (e.g. with `ws`) will cause Node to hang during SSR.
For SSR set 'ssr: false' in your query options for subscription queries.
*/
if (!ssr) {
// The endpoint for Sitecore is the same as the HTTP(s) endpoint, but with ws:// or wss:// (encrypted)
const subscriptionsEndpointUrl = endpoint.replace(/^http(s?)/, 'ws$1');
constructor() {
this.client = new Apollo.ApolloClient({
cache,
link: new BatchHttpLink({
uri: `${constants.API_URL}/graphql`,
// To keep the same express session information with each request
credentials: 'include'
})
});
}
/**
* Maps GraphQL object
* @param {object} object
*/
function customIdMapper(object) {
switch (object.__typename) {
case 'ArticleReply':
return `${object.__typename}:${object.articleId}__${object.replyId}`;
default:
// fall back to default handling
return defaultDataIdFromObject(object);
}
}
const config = {
link: new BatchHttpLink({
uri: `${PUBLIC_API_URL}/graphql`, // Server URL (must be absolute)
headers,
credentials: 'include', // Additional fetch() options like `credentials` or `headers`
}),
createCache() {
return new InMemoryCache({ dataIdFromObject: customIdMapper });
},
};
export default withData(config);