-
Notifications
You must be signed in to change notification settings - Fork 210
Add offline transactions support for capacitor #1246
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
curebasemarco
wants to merge
4
commits into
TanStack:main
Choose a base branch
from
curebasemarco:feature/add-offline-transactions-support-capacitor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
001d225
feat: add offline transactions support for capacitor
curebasemarco 46fc0ff
chore: add changeset
curebasemarco 95b2759
fix: ensure packages are correct declared on vite.config
curebasemarco 7237247
typo: comments on barrel exports
curebasemarco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@tanstack/offline-transactions': minor | ||
| --- | ||
|
|
||
| Add support for capacitor on offline-transactions |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
packages/offline-transactions/src/capacitor/OfflineExecutor.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import { OfflineExecutor as BaseOfflineExecutor } from '../OfflineExecutor' | ||
| import { CapacitorOnlineDetector } from '../connectivity/CapacitorOnlineDetector' | ||
| import { CapacitorStorageAdapter } from '../storage/CapacitorStorageAdapter' | ||
| import type { OfflineConfig } from '../types' | ||
|
|
||
| export class OfflineExecutor extends BaseOfflineExecutor { | ||
| constructor(config: OfflineConfig) { | ||
| super({ | ||
| ...config, | ||
| storage: config.storage ?? new CapacitorStorageAdapter(), | ||
| onlineDetector: config.onlineDetector ?? new CapacitorOnlineDetector(), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| export function startOfflineExecutor(config: OfflineConfig): OfflineExecutor { | ||
| return new OfflineExecutor(config) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| // Re-export from main entry (types, utilities, etc.) | ||
| export { | ||
| // Types | ||
| type OfflineTransaction, | ||
| type OfflineConfig, | ||
| type OfflineMode, | ||
| type StorageAdapter, | ||
| type StorageDiagnostic, | ||
| type StorageDiagnosticCode, | ||
| type RetryPolicy, | ||
| type LeaderElection, | ||
| type OnlineDetector, | ||
| type CreateOfflineTransactionOptions, | ||
| type CreateOfflineActionOptions, | ||
| type SerializedError, | ||
| type SerializedMutation, | ||
| NonRetriableError, | ||
| // Storage adapters | ||
| IndexedDBAdapter, | ||
| LocalStorageAdapter, | ||
| // Retry policies | ||
| DefaultRetryPolicy, | ||
| BackoffCalculator, | ||
| // Coordination | ||
| WebLocksLeader, | ||
| BroadcastChannelLeader, | ||
| // Connectivity - export web detector too for flexibility | ||
| WebOnlineDetector, | ||
| DefaultOnlineDetector, | ||
| // API components | ||
| OfflineTransactionAPI, | ||
| createOfflineAction, | ||
| // Outbox management | ||
| OutboxManager, | ||
| TransactionSerializer, | ||
| // Execution engine | ||
| KeyScheduler, | ||
| TransactionExecutor, | ||
| } from '../index' | ||
|
|
||
| // Export RN-specific detector | ||
| export { CapacitorOnlineDetector } from '../connectivity/CapacitorOnlineDetector' | ||
|
|
||
| // Export Capacitor-configured executor | ||
| export { OfflineExecutor, startOfflineExecutor } from './OfflineExecutor' | ||
98 changes: 98 additions & 0 deletions
98
packages/offline-transactions/src/connectivity/CapacitorOnlineDetector.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import { Network } from '@capacitor/network' | ||
| import type { OnlineDetector } from '../types' | ||
|
|
||
| interface ListenerHandle { | ||
| remove: () => Promise<void> | ||
| } | ||
|
|
||
| export class CapacitorOnlineDetector implements OnlineDetector { | ||
| private listeners: Set<() => void> = new Set() | ||
| private networkListenerHandle: ListenerHandle | null = null | ||
| private isListening = false | ||
| private wasConnected = true | ||
|
|
||
| constructor() { | ||
| this.startListening() | ||
| } | ||
|
|
||
| private startListening(): void { | ||
| if (this.isListening) { | ||
| return | ||
| } | ||
|
|
||
| this.isListening = true | ||
|
|
||
| Network.addListener(`networkStatusChange`, (status) => { | ||
| const isConnected = status.connected | ||
|
|
||
| if (isConnected && !this.wasConnected) { | ||
| this.notifyListeners() | ||
| } | ||
|
|
||
| this.wasConnected = isConnected | ||
| }).then((handle) => { | ||
| this.networkListenerHandle = handle | ||
| }) | ||
|
|
||
| if (typeof document !== `undefined`) { | ||
| document.addEventListener(`visibilitychange`, this.handleVisibilityChange) | ||
| } | ||
| } | ||
|
|
||
| private handleVisibilityChange = (): void => { | ||
| if (document.visibilityState === `visible`) { | ||
| this.notifyListeners() | ||
| } | ||
| } | ||
|
|
||
| private stopListening(): void { | ||
| if (!this.isListening) { | ||
| return | ||
| } | ||
|
|
||
| this.isListening = false | ||
|
|
||
| if (this.networkListenerHandle) { | ||
| this.networkListenerHandle.remove() | ||
| this.networkListenerHandle = null | ||
| } | ||
|
|
||
| if (typeof document !== `undefined`) { | ||
| document.removeEventListener( | ||
| `visibilitychange`, | ||
| this.handleVisibilityChange, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private notifyListeners(): void { | ||
| for (const listener of this.listeners) { | ||
| try { | ||
| listener() | ||
| } catch (error) { | ||
| console.warn(`CapacitorOnlineDetector listener error:`, error) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| subscribe(callback: () => void): () => void { | ||
| this.listeners.add(callback) | ||
|
|
||
| return () => { | ||
| this.listeners.delete(callback) | ||
|
|
||
| if (this.listeners.size === 0) { | ||
| this.stopListening() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| notifyOnline(): void { | ||
| this.notifyListeners() | ||
| } | ||
|
|
||
| dispose(): void { | ||
| this.stopListening() | ||
| this.listeners.clear() | ||
| } | ||
| } |
85 changes: 85 additions & 0 deletions
85
packages/offline-transactions/src/storage/CapacitorStorageAdapter.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| import { Preferences } from '@capacitor/preferences' | ||
| import { BaseStorageAdapter } from './StorageAdapter' | ||
|
|
||
| export class CapacitorStorageAdapter extends BaseStorageAdapter { | ||
| private prefix: string | ||
|
|
||
| constructor(prefix = `offline-tx:`) { | ||
| super() | ||
| this.prefix = prefix | ||
| } | ||
|
|
||
| static async probe(): Promise<{ available: boolean; error?: Error }> { | ||
| try { | ||
| const testKey = `__offline-tx-probe__` | ||
| const testValue = `test` | ||
|
|
||
| await Preferences.set({ key: testKey, value: testValue }) | ||
| const { value: retrieved } = await Preferences.get({ key: testKey }) | ||
| await Preferences.remove({ key: testKey }) | ||
|
|
||
| if (retrieved !== testValue) { | ||
| return { | ||
| available: false, | ||
| error: new Error(`Capacitor Preferences read/write verification failed`), | ||
| } | ||
| } | ||
|
|
||
| return { available: true } | ||
| } catch (error) { | ||
| return { | ||
| available: false, | ||
| error: error instanceof Error ? error : new Error(String(error)), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private getKey(key: string): string { | ||
| return `${this.prefix}${key}` | ||
| } | ||
|
|
||
| async get(key: string): Promise<string | null> { | ||
| try { | ||
| const { value } = await Preferences.get({ key: this.getKey(key) }) | ||
| return value | ||
| } catch (error) { | ||
| console.warn(`Capacitor Preferences get failed:`, error) | ||
| return null | ||
| } | ||
| } | ||
|
|
||
| async set(key: string, value: string): Promise<void> { | ||
| await Preferences.set({ key: this.getKey(key), value }) | ||
| } | ||
|
|
||
| async delete(key: string): Promise<void> { | ||
| try { | ||
| await Preferences.remove({ key: this.getKey(key) }) | ||
| } catch (error) { | ||
| console.warn(`Capacitor Preferences delete failed:`, error) | ||
| } | ||
| } | ||
|
|
||
| async keys(): Promise<Array<string>> { | ||
| try { | ||
| const { keys } = await Preferences.keys() | ||
| return keys | ||
| .filter((key) => key.startsWith(this.prefix)) | ||
| .map((key) => key.slice(this.prefix.length)) | ||
| } catch (error) { | ||
| console.warn(`Capacitor Preferences keys failed:`, error) | ||
| return [] | ||
| } | ||
| } | ||
|
|
||
| async clear(): Promise<void> { | ||
| try { | ||
| const prefixedKeys = await this.keys() | ||
| await Promise.all( | ||
| prefixedKeys.map((key) => Preferences.remove({ key: this.getKey(key) })) | ||
| ) | ||
| } catch (error) { | ||
| console.warn(`Capacitor Preferences clear failed:`, error) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.