成功重试时@client阿波罗链接突变



我在网络错误导致的重试时在我的 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的良好重试逻辑,并在逻辑进行时额外发出一些状态进行缓存。

我通过做两件事实现了预期的行为:

通过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()
}
})
})

最新更新