由于网络错误导致重试时,我正在React应用程序中呈现通知。如果/建立连接(重试成功),我希望清除所有此类通知
我使用apollo-link-retry
并使用自定义attempts
回调在重试循环开始和超时时对缓存进行突变。可以,但是成功重试时通知会保留在屏幕上,因为成功重试后不会调用回调,所以我无法从缓存中清除通知。
我尝试使用具有类似问题的apollo-link-error
实现类似的逻辑。仅当发生错误并且成功重试不是错误时,才会调用链接。
这是我对apollo-link-retry
的配置,“几乎”有效:
const retryLink = new RetryLink({
attempts: (count) => {
let notifyType
let shouldRetry = true
if (count === 1) {
notifyType = 'CONNECTION_RETRY'
shouldRetry = true
} else if (count <= 30) {
shouldRetry = true
} else {
notifyType = 'CONNECTION_TIMEOUT'
shouldRetry = false
}
if (notifyType) {
client.mutate({
mutation: gql`
mutation m($notification: Notification!) {
raiseNotification(notification: $notification) @client
}
`,
variables: {
notification: { type: notifyType }
}
})
}
return shouldRetry
}
})
也许我需要实现一个自定义链接才能完成此任务?我希望找到一种方法来利用apollo-link-retry
的不错的重试逻辑,并随着逻辑的进行进一步发出一些要缓存的状态。
答案 0 :(得分:0)
我通过做两件事实现了预期的行为:
通过attempts
函数在链接上下文中保持重试计数:
new RetryLink({
delay: {
initial: INITIAL_RETRY_DELAY,
max: MAX_RETRY_DELAY,
jitter: true
},
attempts: (count, operation, error) => {
if (!error.message || error.message !== 'Failed to fetch') {
// If error is not related to connection, do not retry
return false
}
operation.setContext(context => ({ ...context, retryCount: count }))
return (count <= MAX_RETRY_COUNT)
}
})
实施自定义链接,该链接将错误和已完成的事件订阅到链接链的更下方,并使用新的上下文字段来决定是否引发通知:
new ApolloLink((operation, forward) => {
const context = operation.getContext()
return new Observable(observer => {
let subscription, hasApplicationError
try {
subscription = forward(operation).subscribe({
next: result => {
if (result.errors) {
// Encountered application error (not network related)
hasApplicationError = true
notifications.raiseNotification(apolloClient, 'UNEXPECTED_ERROR')
}
observer.next(result)
},
error: networkError => {
// Encountered network error
if (context.retryCount === 1) {
// Started retrying
notifications.raiseNotification(apolloClient, 'CONNECTION_RETRY')
}
if (context.retryCount === MAX_RETRY_COUNT) {
// Timed out after retrying
notifications.raiseNotification(apolloClient, 'CONNECTION_TIMEOUT')
}
observer.error(networkError)
},
complete: () => {
if (!hasApplicationError) {
// Completed successfully after retrying
notifications.clearNotification(apolloClient)
}
observer.complete.bind(observer)()
},
})
} catch (e) {
observer.error(e)
}
return () => {
if (subscription) subscription.unsubscribe()
}
})
})