本文整理汇总了TypeScript中apollo-link-error.onError函数的典型用法代码示例。如果您正苦于以下问题:TypeScript onError函数的具体用法?TypeScript onError怎么用?TypeScript onError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了onError函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。
示例1: constructor
constructor(apollo: Apollo, httpLink: HttpLink) {
const http = httpLink.create({ uri: `${environment.apiAddress}/graphql` });
const middleware = setContext(() => ({
headers: new HttpHeaders().set(
'Sandwich-Auth-Token',
localStorage.getItem('token') || ''
)
}));
const error = onError(({ networkError, graphQLErrors }) => {
console.error(networkError);
window.location.pathname = '/login';
});
const link = middleware.concat(error).concat(http);
apollo.create({
link,
cache: new InMemoryCache({
dataIdFromObject: (o: any) => {
let key;
switch (o.__typename) {
case 'user':
key = `${o.__typename}-${o.userId},`;
break;
case 'week':
key = `${o.__typename}-${o.weekId},`;
break;
case 'weekUserLink':
key = `${o.__typename}-${o.weekId}-${o.userId},`;
break;
default:
key = `${o.__typename}-${o.id},`;
break;
}
return key;
}
})
});
}
开发者ID:FraserKillip,项目名称:SC2_WEB,代码行数:43,代码来源:app.module.ts
示例2: createErrorLink
function createErrorLink(modalService: ModalService) {
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}`);
const inputs = {
isMobile: false
};
// modalService.init(ErrorModalComponent, inputs, {});
}
});
return errorLink;
}
开发者ID:ngocdiep,项目名称:nd,代码行数:21,代码来源:error.ts
示例3: onError
export const invalidTokenLinkWithTokenHandlerComponent = (
component: React.ComponentClass
): { component: React.FC<any>; link: ApolloLink } => {
// tslint:disable-next-line:no-empty
let tokenExpirationCallback = () => {};
const tokenExpirationHandler = callback => {
tokenExpirationCallback = callback;
};
const extendedComponent = props => {
return React.createElement(component, {
...props,
tokenExpirationHandler
});
};
const link = onError((error: ResponseError) => {
if (error.networkError && error.networkError.statusCode === 401) {
tokenExpirationCallback();
}
});
return { component: extendedComponent, link };
};
开发者ID:p2p-ms,项目名称:front,代码行数:22,代码来源:auth.ts
示例4: createClient
export function createClient(
// @ts-ignore - useful to pass in the store for `Authorization` headers, etc
store: Store
): ApolloClient<NormalizedCacheObject> {
// Create the cache first, which we'll share across Apollo tooling.
// This is an in-memory cache. Since we'll be calling `createClient` on
// universally, the cache will survive until the HTTP request is
// responded to (on the server) or for the whole of the user's visit (in
// the browser)
const cache = new InMemoryCache({ fragmentMatcher });
// Create a HTTP client (both server/client). It takes the GraphQL
// server from the `GRAPHQL` environment variable, which by default is
// set to an external playground at https://graphqlhub.com/graphql
const httpLink = new HttpLink({
credentials: "same-origin",
uri: GRAPHQL
});
// If we're in the browser, we'd have received initial state from the
// server. Restore it, so the client app can continue with the same data.
if (!SERVER) {
cache.restore((window as any).__APOLLO__);
}
// Return a new Apollo Client back, with the cache we've just created,
// and an array of 'links' (Apollo parlance for GraphQL middleware)
// to tell Apollo how to handle GraphQL requests
return new ApolloClient({
cache,
link: ApolloLink.from([
// General error handler, to log errors back to the console.
// Replace this in production with whatever makes sense in your
// environment. Remember you can use the global `SERVER` variable to
// determine whether you're running on the server, and record errors
// out to third-party services, etc
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}`);
}
}),
// Split on HTTP and WebSockets
WS_SUBSCRIPTIONS && !SERVER
? split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
// Use WebSockets for subscriptions
new WebSocketLink(
// Replace http(s) with `ws` for connecting via WebSockts
new SubscriptionClient(GRAPHQL.replace(/^https?/, "ws"), {
reconnect: true // <-- automatically redirect as needed
})
),
// ... fall-back to HTTP for everything else
httpLink
)
: httpLink // <-- just use HTTP on the server
]),
// On the server, enable SSR mode
ssrMode: SERVER
});
}
开发者ID:leebenson,项目名称:cli,代码行数:75,代码来源:apollo.ts
示例5: split
});
const combinedLinks = split(
({ query }) => {
const { kind, operation }: any = getMainDefinition(query);
return kind === "OperationDefinition" && operation === "subscription";
},
wsLink,
httpLink
);
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message }) => {
toast.error(`Unexpected error: ${message}`);
});
}
if (networkError) {
toast.error(`Network error: ${networkError}`);
}
});
const localStateLink = withClientState({
cache,
defaults: {
auth: {
__typename: "Auth",
isLoggedIn: Boolean(localStorage.getItem("jwt"))
}
},
resolvers: {
Mutation: {
开发者ID:piann,项目名称:weber-client,代码行数:32,代码来源:apollo.ts
示例6: constructor
constructor(config: PresetConfig) {
const cache =
config && config.cacheRedirects
? new InMemoryCache({ cacheRedirects: config.cacheRedirects })
: new InMemoryCache();
const stateLink =
config && config.clientState
? withClientState({ ...config.clientState, cache })
: false;
const errorLink =
config && config.onError
? onError(config.onError)
: 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}`);
});
const requestHandler =
config && config.request
? new ApolloLink((operation, forward) =>
new Observable(observer => {
let handle: any;
Promise.resolve(operation)
.then(oper => config.request(oper))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return () => {
if (handle) handle.unsubscribe;
};
})
)
: false;
const httpLink = new HttpLink({
uri: (config && config.uri) || '/graphql',
fetchOptions: (config && config.fetchOptions) || {},
credentials: 'same-origin',
});
const link = ApolloLink.from([
errorLink,
requestHandler,
stateLink,
httpLink,
].filter(x => !!x) as ApolloLink[]);
// super hacky, we will fix the types eventually
super({ cache, link } as any);
}
开发者ID:NewSpring,项目名称:apollo-client,代码行数:63,代码来源:index.ts
示例7: constructor
constructor(config: PresetConfig = {}) {
if (config) {
const diff = Object.keys(config).filter(
key => PRESET_CONFIG_KEYS.indexOf(key) === -1,
);
if (diff.length > 0) {
invariant.warn(
'ApolloBoost was initialized with unsupported options: ' +
`${diff.join(' ')}`,
);
}
}
const {
request,
uri,
credentials,
headers,
fetch,
fetchOptions,
clientState,
cacheRedirects,
onError: errorCallback,
name,
version,
resolvers,
typeDefs,
fragmentMatcher,
} = config;
let { cache } = config;
invariant(
!cache || !cacheRedirects,
'Incompatible cache configuration. If providing `cache` then ' +
'configure the provided instance with `cacheRedirects` instead.',
);
if (!cache) {
cache = cacheRedirects
? new InMemoryCache({ cacheRedirects })
: new InMemoryCache();
}
const errorLink = errorCallback
? onError(errorCallback)
: onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
// tslint:disable-next-line
invariant.warn(
`[GraphQL error]: Message: ${message}, Location: ` +
`${locations}, Path: ${path}`,
),
);
}
if (networkError) {
// tslint:disable-next-line
invariant.warn(`[Network error]: ${networkError}`);
}
});
const requestHandler = request
? new ApolloLink(
(operation, forward) =>
new Observable(observer => {
let handle: any;
Promise.resolve(operation)
.then(oper => request(oper))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return () => {
if (handle) {
handle.unsubscribe();
}
};
}),
)
: false;
const httpLink = new HttpLink({
uri: uri || '/graphql',
fetch,
fetchOptions: fetchOptions || {},
credentials: credentials || 'same-origin',
headers: headers || {},
});
const link = ApolloLink.from([errorLink, requestHandler, httpLink].filter(
x => !!x,
) as ApolloLink[]);
//.........这里部分代码省略.........
开发者ID:apollostack,项目名称:apollo-client,代码行数:101,代码来源:index.ts
示例8: toIdValue
Query: {
device: (_, args) =>
toIdValue(
cache.config.dataIdFromObject({__typename: 'Device', id: args.id}),
),
},
},
})
export const client = new ApolloClient({
link: ApolloLink.from([
onError(({graphQLErrors, networkError}) => {
if (graphQLErrors)
graphQLErrors.map(({message, locations, path}) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
)
if (networkError) console.error(`[Network error]: ${networkError}`)
}),
link,
]),
cache,
})
const reducer = combineReducers({
mainScreen: mainScreenReducer,
snackbar: snackbarReducer,
} as any)
const composeEnhancers =
开发者ID:Pajn,项目名称:RAXA,代码行数:31,代码来源:store.ts
示例9: createApolloClient
export function createApolloClient() {
const graphqlApiUrl = getGraphQLEndpoint(
process.env.REACT_APP_LOCAL_API ? 'graphqlApiUrlLocal' : 'graphqlApiUrl',
);
const httpLink = createHttpLink({ uri: graphqlApiUrl });
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: appInitializer.getBearerToken() || null,
},
};
});
const subscriptionsApiUrl = getGraphQLEndpoint(
process.env.REACT_APP_LOCAL_API
? 'subscriptionsApiUrlLocal'
: 'subscriptionsApiUrl',
);
const wsLink = new WebSocketLink({
uri: subscriptionsApiUrl,
options: {
reconnect: true,
},
});
const cache = new InMemoryCache();
const authHttpLink = authLink.concat(httpLink);
const errorLink = onError(
({ operation, response, graphQLErrors, networkError }) => {
if (process.env.REACT_APP_ENV !== 'production') {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
// tslint:disable-next-line
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
}
// tslint:disable-next-line
if (networkError) console.error(`[Network error]: ${networkError}`);
}
},
);
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
authHttpLink,
);
const client = new ApolloClient({
link: ApolloLink.from([errorLink, link]),
cache,
connectToDevTools: true,
});
return client;
}
开发者ID:marynaKhromova,项目名称:console,代码行数:63,代码来源:apollo-client.ts
注:本文中的apollo-link-error.onError函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论