Skip to content

Commit

Permalink
feat: Forward operation in StackLink.request() on Network error
Browse files Browse the repository at this point in the history
On the Flagship app we want to serve `.query()` request using the
`StackLink` when the device is connected, but we want to fallback to
the `PouchLink` when we detect a connection loss

In previous commit we tried pro-actively detect for connexion loss by
calling an `isOnline()` method before processing the request

But we want to also catch network errors when the `isOnline()` methods
fails to detect connection loss, then we also fallback to the next
`Link`
  • Loading branch information
Ldoppea committed Jul 17, 2024
1 parent 2f20fd5 commit 9c05e2c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
14 changes: 11 additions & 3 deletions packages/cozy-client/src/StackLink.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import CozyLink from './CozyLink'
import { DOCTYPE_FILES } from './const'
import { BulkEditError } from './errors'
import logger from './logger'
import { isReactNativeOfflineError } from './utils'

/**
*
Expand Down Expand Up @@ -84,10 +85,17 @@ export default class StackLink extends CozyLink {
return forward(operation)
}

if (operation.mutationType) {
return this.executeMutation(operation, result, forward)
try {
if (operation.mutationType) {
return await this.executeMutation(operation, result, forward)
}
return await this.executeQuery(operation)
} catch (err) {
if (isReactNativeOfflineError(err)) {
return forward(operation)
}
throw err
}
return this.executeQuery(operation)
}

async persistData(data, forward) {
Expand Down
12 changes: 12 additions & 0 deletions packages/cozy-client/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,15 @@ export const hasQueriesBeenLoaded = queriesResults => {
hasQueryBeenLoaded(queryResult)
)
}

/**
* Check is the error is about ReactNative not having access to internet
*
* @param {Error} err - The error to check
* @returns {boolean} True if the error is a network error, otherwise false
*/
export const isReactNativeOfflineError = err => {
// This error message is specific to ReactNative
// Network errors on a browser would produce another error.message
return err.message === 'Network request failed'
}

0 comments on commit 9c05e2c

Please sign in to comment.