Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export default function createApolloClient() {
// "apollo-link" is a standard interface for modifying control flow of GraphQL requests and fetching GraphQL results,
// designed to provide a simple GraphQL client that is capable of extensions.
// https://github.com/apollographql/apollo-link
const link = from([
// Handle and inspect errors in your GraphQL network stack.
// https://github.com/apollographql/apollo-link/tree/master/packages/apollo-link-error
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
);
}
if (networkError) {
console.warn(`[Network error]: ${networkError}`);
}
}),
// HTTP Link takes an object with some options on it to customize the behavior of the link.
// If your server supports it, the HTTP link can also send over metadata about the request in the extensions field.
// https://github.com/apollographql/apollo-link/tree/master/packages/apollo-link-http
retryIf: async (error) => {
if (error && error.result && error.result.status === 401) {
await this.refreshToken(0, /* shouldRetry */ false);
}
return true;
},
},
});
const link = split(({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === "OperationDefinition" && operation === "subscription";
},
subscriptionLink,
from([retryLink, this.authLink, httpLink]));
return new ApolloClient({
link,
cache,
});
}
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
const httpLink = new HttpLink({
uri: 'https://api.github.com/graphql', // 配置请求url
headers: { // 配置header
Authorization: `Bearer ${token}`
}
})
const cache = new InMemoryCache() // 缓存
export default new ApolloClient({
link: from([Middleware, Afterware, errorLink, httpLink]),
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'network-only',
errorPolicy: 'all',
},
mutate: {
errorPolicy: 'all'
}
}
})
const graphQLConfig = Config.getSection('SilverStripe\\Admin\\LeftAndMain').graphql;
const cachedTypenames = graphQLConfig && graphQLConfig.cachedTypenames;
let fragmentData;
// GraphQL may not return what we want (e.g. if schema is empty, so fail gracefully)
try {
fragmentData = await getGraphqlFragments(baseUrl, cachedTypenames);
} catch (e) {
fragmentData = null;
}
const cache = buildCache(fragmentData);
const components = buildNetworkComponents(baseUrl);
const stateLink = withClientState({
cache,
resolvers: {}
});
const link = from([stateLink, ...components]);
return new ApolloClient({ cache, link });
};
//
// The `apollo-link-state` approach uses a custom link chain to parse
// and execute queries, whereas the Apollo Client local state approach
// uses Apollo Client directly. To decide which approach to use
// below, we'll check to see if typeDefs have been set on the
// ApolloClient instance, as if so, this means Apollo Client local state
// is being used.
const supportsApolloClientLocalState =
typeof apolloClient.typeDefs !== "undefined";
if (!supportsApolloClientLocalState) {
// Supports `apollo-link-state`.
const context = { __devtools_key__: key, cache };
const devtoolsLink = from([
errorLink(),
cacheLink(fetchPolicy),
schemaLink(),
userLink,
]);
const operationExecution$ = execute(devtoolsLink, {
query: queryAst,
variables,
operationName,
context,
});
operationExecution$.subscribe(subscriptionHandlers);
return;
}
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
)
if (networkError){
console.log(`[Network error]: ${networkError}`)
}
});
return new ApolloClient({
link: from([
afterwareLink,
errorLink,
middlewareLink,
httpLink,
]),
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
errorPolicy: 'ignore',
fetchPolicy: 'network-only',
},
query: {
errorPolicy: 'apollo-link',
},
mutate: {
errorPolicy: 'all',
: apolloContext,
})
: new HttpLink({
uri: endpoint,
credentials: includeCredentials,
fetch,
});
const links: Array = getApolloLinks
? getApolloLinks([connectionLink], ctx)
: [connectionLink];
const client = new ApolloClient({
ssrMode: __NODE__,
connectToDevTools: __BROWSER__ && __DEV__,
link: apolloLinkFrom(links),
cache: cache.restore(initialState),
resolvers,
typeDefs,
defaultOptions,
});
return client;
}
return (ctx: Context, initialState: mixed) => {
const subscriber = request => {
const { query, variables, operationName, key, fetchPolicy } = JSON.parse(
request,
);
try {
const userLink = hook.ApolloClient.link;
const cache = hook.ApolloClient.cache;
const devtoolsLink = from([
errorLink(),
cacheLink(fetchPolicy),
schemaLink(),
userLink,
]);
const obs = execute(devtoolsLink, {
query: gql(query),
variables,
operationName,
context: { __devtools_key__: key, cache },
});
obs.subscribe({
next: data => bridge.send(`link:next:${key}`, JSON.stringify(data)),
error: err => bridge.send(`link:error:${key}`, JSON.stringify(err)),
complete: () => bridge.send(`link:complete:${key}`),
});