如何将令牌设置为 onError ApolloClient?
Posted
技术标签:
【中文标题】如何将令牌设置为 onError ApolloClient?【英文标题】:How to set token into onError ApolloClient? 【发布时间】:2019-09-28 22:01:27 【问题描述】:如果返回错误将再次调用 setContext 进行查询,我想处理错误,但我无法在本地状态下获取令牌,因为 onError 不接受异步。我怎么能做到这一点。 谢谢
//
export default async () =>
new ApolloClient(
cache: new InMemoryCache(
dataIdFromObject: object => object.key || null
),
uri: Api.GRAPH_QL_URL,
clientState: defaults, resolvers ,
// cho handle network failed
///onError not accept async
onError: ( graphQLErrors, networkError, operation, forward ) =>
// how to get token in hear
if (networkError)
operation.setContext(
headers:
Accept: "application/json",
authorization: token !== null ? `JWT $token` : "" // how to put token into authorization
);
,
// Call query
request: async operation =>
const token = await AsyncStorage.getItem(strings.keyToken);
console.log("Client request: ",
operationName: operation.operationName,
variables: operation.variables,
query: operation.query,
jwtoken: token
);
operation.setContext(
headers:
Accept: "application/json",
authorization: token !== null ? `JWT $token` : ""
);
,
);
//I want to handle error if return error will call setContext for query again but I can't get token in local state. How I can do that.
Thanks
【问题讨论】:
【参考方案1】:您需要设置一个 Observable 才能在 onError
方法中使用 async/await
。
从apollo-link
(import Observable from 'apollo-link';
) 导入。
onError: ( graphQLErrors, networkError, operation, forward ) =>
if (networkError)
return new Observable(async (observer) =>
const token = await AsyncStorage.getItem(strings.keyToken);
const headers = operation.getContext().headers;
operation.setContext(
headers:
...headers,
Authorization: token !== null ? `JWT $token` : ''
);
const subscriber =
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
;
return forward(operation).subscribe(subscriber);
);
【讨论】:
以上是关于如何将令牌设置为 onError ApolloClient?的主要内容,如果未能解决你的问题,请参考以下文章
如何将令牌设置为 Java 中获取请求的 HTTPHeader?
如何使用 Alamofire 的 RequestAdapter 将 firebase ID 令牌设置为全局标头?
如何在flutter中将token设置为全局变量?所以我可以随时随地访问令牌