async-storage-sync 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -153
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# async-storage-sync
|
|
2
2
|
|
|
3
|
-
**Offline-first data layer for React Native** —
|
|
3
|
+
**Offline-first data layer for React Native** — save locally, sync to your server when connected.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -8,213 +8,190 @@
|
|
|
8
8
|
npm install async-storage-sync @react-native-async-storage/async-storage @react-native-community/netinfo
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
## Quick Start
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
Initialize once in your app (no separate files required):
|
|
13
|
+
**1. Initialize once in `App.tsx`:**
|
|
16
14
|
|
|
17
15
|
```ts
|
|
18
|
-
// App.tsx
|
|
19
|
-
import React, { useEffect } from 'react';
|
|
20
16
|
import { initSyncQueue } from 'async-storage-sync';
|
|
21
17
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
return <YourApp />;
|
|
34
|
-
}
|
|
18
|
+
initSyncQueue({
|
|
19
|
+
driver: 'asyncstorage',
|
|
20
|
+
serverUrl: 'https://api.example.com',
|
|
21
|
+
credentials: {
|
|
22
|
+
Authorization: 'Token abc123',
|
|
23
|
+
'x-api-key': 'my-custom-key',
|
|
24
|
+
},
|
|
25
|
+
endpoint: '/submit',
|
|
26
|
+
autoSync: true,
|
|
27
|
+
});
|
|
35
28
|
```
|
|
36
29
|
|
|
37
|
-
|
|
30
|
+
**2. Save data anywhere in your app:**
|
|
38
31
|
|
|
39
32
|
```ts
|
|
40
33
|
import { getSyncQueue } from 'async-storage-sync';
|
|
41
34
|
|
|
42
35
|
const store = getSyncQueue();
|
|
43
36
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
timestamp: new Date().toISOString()
|
|
37
|
+
await store.save('submissions', {
|
|
38
|
+
formId: '123',
|
|
39
|
+
name: 'John',
|
|
40
|
+
timestamp: new Date().toISOString(),
|
|
49
41
|
});
|
|
50
|
-
|
|
51
|
-
// Sync and get summary result
|
|
52
|
-
const result = await store.flushWithResult();
|
|
53
|
-
console.log(`Synced: ${result.synced}, Failed: ${result.failed}, Remaining: ${result.remainingPending}`);
|
|
54
|
-
|
|
55
|
-
// List pending records
|
|
56
|
-
const pending = await store.getAll('forms');
|
|
57
|
-
console.log(`${pending.length} forms waiting to sync`);
|
|
58
42
|
```
|
|
59
43
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
- `autoSync: true` (default): when the app starts, the package checks connectivity and attempts sync if online.
|
|
63
|
-
- `autoSync: true` also listens for reconnect events and retries pending items automatically.
|
|
64
|
-
- `autoSyncCollections` (optional): when set, auto-sync on reconnect targets only those collections.
|
|
65
|
-
- `autoSync: false`: no automatic syncing; call sync methods manually when you choose.
|
|
66
|
-
- Manual methods:
|
|
67
|
-
- `store.flushWithResult()` → sync all pending and return summary counts
|
|
68
|
-
- `store.syncWithResult(collection)` → sync one collection and return summary counts
|
|
69
|
-
- `store.syncManyWithResult(collections)` → sync only selected collections and return merged summary counts
|
|
70
|
-
- `store.syncById(collection, id)` → sync one record
|
|
71
|
-
- Sync destination is controlled by your config: `serverUrl + endpoint`.
|
|
44
|
+
**3. Sync and check the result:**
|
|
72
45
|
|
|
73
|
-
## API Reference
|
|
74
|
-
|
|
75
|
-
### Setup
|
|
76
|
-
|
|
77
|
-
| Function | Purpose |
|
|
78
|
-
|--------|---------|
|
|
79
|
-
| `initSyncQueue(config)` | Initialize singleton once at app startup (safe to call repeatedly) |
|
|
80
|
-
| `getSyncQueue()` | Get initialized singleton instance |
|
|
81
|
-
| `setStorageDriver(storage)` | Inject storage client explicitly (useful for symlink/local package setups) |
|
|
82
|
-
|
|
83
|
-
### Store Methods (`const store = getSyncQueue()`)
|
|
84
|
-
|
|
85
|
-
| Method | Purpose |
|
|
86
|
-
|--------|---------|
|
|
87
|
-
| `store.save(collection, data, options?)` | Save one record locally and enqueue for sync |
|
|
88
|
-
| `store.getAll(collection)` | Get all records from one collection |
|
|
89
|
-
| `store.getById(collection, id)` | Get one record by internal `_id` |
|
|
90
|
-
| `store.deleteById(collection, id)` | Delete one record by internal `_id` |
|
|
91
|
-
| `store.deleteCollection(collection)` | Delete all records in one collection |
|
|
92
|
-
| `store.flushWithResult()` | Sync all pending and return detailed summary (`attempted`, `synced`, `failed`, `retried`, `remainingPending`, `items`) |
|
|
93
|
-
| `store.syncWithResult(collection)` | Sync collection and return detailed summary (same format as `flushWithResult()`) |
|
|
94
|
-
| `store.syncManyWithResult(collections)` | Sync selected collections and return one merged summary (same format as `flushWithResult()`) |
|
|
95
|
-
| `store.syncById(collection, id)` | Sync one specific record by internal `_id` |
|
|
96
|
-
| `store.requeueFailed()` | Move `failed` records back to pending queue for retry |
|
|
97
|
-
| `store.onSynced(callback)` | Event callback for successful sync of each item |
|
|
98
|
-
| `store.onAuthError(callback)` | Event callback when sync returns `401` or `403` |
|
|
99
|
-
| `store.onStorageFull(callback)` | Event callback when local storage is full on save |
|
|
100
|
-
| `store.getQueue()` | Inspect in-memory queue items (debug/metrics) |
|
|
101
|
-
| `store.destroy()` | Stop engine, clear queue/storage, and reset singleton |
|
|
102
|
-
|
|
103
|
-
## Quick Examples
|
|
104
|
-
|
|
105
|
-
**Auto-sync when internet reconnects:**
|
|
106
46
|
```ts
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
NetInfo.addEventListener(state => {
|
|
111
|
-
if (state.isConnected) {
|
|
112
|
-
void getSyncQueue().flushWithResult();
|
|
113
|
-
}
|
|
114
|
-
});
|
|
47
|
+
const result = await store.flushWithResult('submissions');
|
|
48
|
+
console.log(`Synced: ${result.synced}, Failed: ${result.failed}, Remaining: ${result.remainingPending}`);
|
|
115
49
|
```
|
|
116
50
|
|
|
117
|
-
|
|
118
|
-
```ts
|
|
119
|
-
const store = getSyncQueue();
|
|
51
|
+
---
|
|
120
52
|
|
|
121
|
-
|
|
122
|
-
if (statusCode === 401 || statusCode === 403) {
|
|
123
|
-
console.log('Session expired, re-login needed');
|
|
124
|
-
}
|
|
125
|
-
});
|
|
126
|
-
```
|
|
53
|
+
## Configuration
|
|
127
54
|
|
|
128
|
-
**Transform data before sending to server:**
|
|
129
55
|
```ts
|
|
130
56
|
initSyncQueue({
|
|
57
|
+
// required
|
|
131
58
|
driver: 'asyncstorage',
|
|
132
59
|
serverUrl: 'https://api.example.com',
|
|
133
|
-
credentials: {
|
|
60
|
+
credentials: {
|
|
61
|
+
Authorization: 'Token abc123', // sent as-is in request headers
|
|
62
|
+
'x-api-key': 'my-custom-key', // any key/value pair works
|
|
63
|
+
},
|
|
134
64
|
endpoint: '/submit',
|
|
135
|
-
|
|
65
|
+
|
|
66
|
+
// optional
|
|
67
|
+
autoSync: true, // auto-flush on app open + reconnect (default: true)
|
|
68
|
+
autoSyncCollections: ['submissions'], // limit auto-sync to these collections; empty = all
|
|
69
|
+
onSyncSuccess: 'delete', // what to do after a successful sync: 'keep' | 'delete' | 'ttl'
|
|
70
|
+
ttl: 7 * 24 * 60 * 60 * 1000, // used only when onSyncSuccess is 'ttl'
|
|
71
|
+
duplicateStrategy: 'append', // 'append' (default) | 'overwrite'
|
|
72
|
+
payloadTransformer: (record) => { // strip internal fields before sending to server
|
|
136
73
|
const { _id, _ts, _synced, _retries, ...payload } = record;
|
|
137
74
|
return payload;
|
|
138
75
|
},
|
|
139
76
|
});
|
|
140
77
|
```
|
|
141
78
|
|
|
142
|
-
|
|
79
|
+
> `credentials` values are merged directly into request headers. Any key/value pair is supported.
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## API
|
|
84
|
+
|
|
85
|
+
### Setup
|
|
86
|
+
|
|
143
87
|
```ts
|
|
144
|
-
initSyncQueue(
|
|
145
|
-
|
|
146
|
-
serverUrl: 'https://api.example.com',
|
|
147
|
-
credentials: {
|
|
148
|
-
Authorization: 'Token abc123',
|
|
149
|
-
'x-api-key': 'my-custom-key',
|
|
150
|
-
},
|
|
151
|
-
endpoint: '/submit',
|
|
152
|
-
});
|
|
88
|
+
initSyncQueue(config) // call once at app startup — safe to call again, won't re-init
|
|
89
|
+
getSyncQueue() // get the instance anywhere in your app
|
|
153
90
|
```
|
|
154
91
|
|
|
155
|
-
|
|
92
|
+
### Write
|
|
93
|
+
|
|
156
94
|
```ts
|
|
157
|
-
//
|
|
158
|
-
|
|
95
|
+
store.save(collection, data, options?) // save locally and enqueue for sync
|
|
96
|
+
```
|
|
159
97
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
98
|
+
`options` (all optional, override global config for this call only):
|
|
99
|
+
|
|
100
|
+
| Option | Values | Description |
|
|
101
|
+
|--------|--------|-------------|
|
|
102
|
+
| `type` | `string` | Labels the record — used by `overwrite` strategy to find and replace |
|
|
103
|
+
| `onSyncSuccess` | `'keep'` \| `'delete'` \| `'ttl'` | What happens to the local copy after sync |
|
|
104
|
+
| `duplicateStrategy` | `'append'` \| `'overwrite'` | Whether to add a new record or replace an existing one of the same `type` |
|
|
105
|
+
|
|
106
|
+
### Read
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
store.getAll(collection) // all records in a collection
|
|
110
|
+
store.getById(collection, id) // one record by its _id
|
|
165
111
|
```
|
|
166
112
|
|
|
167
|
-
|
|
113
|
+
### Delete
|
|
114
|
+
|
|
168
115
|
```ts
|
|
169
|
-
|
|
170
|
-
|
|
116
|
+
store.deleteById(collection, id) // remove one record
|
|
117
|
+
store.deleteCollection(collection) // wipe entire collection — call on logout
|
|
171
118
|
```
|
|
172
119
|
|
|
173
|
-
|
|
120
|
+
### Sync
|
|
174
121
|
|
|
175
122
|
```ts
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
endpoint?: '/submit', // route to POST data
|
|
181
|
-
autoSync?: false, // auto-sync on reconnect
|
|
182
|
-
autoSyncCollections?: ['invoices', 'payments'], // optional: only these collections auto-sync on reconnect
|
|
183
|
-
onSyncSuccess?: 'keep', // after sync: keep|delete|ttl
|
|
184
|
-
ttl?: 7 * 24 * 60 * 60 * 1000, // if ttl mode, keep duration
|
|
185
|
-
duplicateStrategy?: 'append', // append or overwrite
|
|
186
|
-
payloadTransformer?: (r) => r, // optional: shape before send
|
|
187
|
-
});
|
|
123
|
+
store.flushWithResult(collection) // sync one collection, get a result summary
|
|
124
|
+
store.syncManyWithResult(collections[]) // sync multiple collections, merged result summary
|
|
125
|
+
store.syncById(collection, id) // sync one specific record
|
|
126
|
+
store.requeueFailed() // move 'failed' records back to pending for retry
|
|
188
127
|
```
|
|
189
128
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
129
|
+
**Result summary shape:**
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
{
|
|
133
|
+
attempted, synced, failed, retried,
|
|
134
|
+
deferred, networkErrors, remainingPending,
|
|
135
|
+
skippedAlreadyFlushing, items
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Events
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
store.onSynced(callback) // fires after each record syncs successfully
|
|
143
|
+
store.onAuthError(callback) // fires on 401/403 — use to trigger re-login
|
|
144
|
+
store.onStorageFull(callback) // fires when device storage is full
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Debug
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
store.getQueue() // inspect the in-memory queue
|
|
151
|
+
store.destroy() // stop engine, clear everything, reset singleton
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
---
|
|
193
155
|
|
|
194
156
|
## How It Works
|
|
195
157
|
|
|
196
|
-
1.
|
|
197
|
-
2.
|
|
198
|
-
3.
|
|
199
|
-
4.
|
|
200
|
-
5.
|
|
201
|
-
6.
|
|
158
|
+
1. `save()` writes the record to AsyncStorage immediately — no network needed.
|
|
159
|
+
2. The record is added to a queue with `_synced: 'pending'`.
|
|
160
|
+
3. On `flushWithResult()` (or automatically on reconnect if `autoSync: true`), queued records are POSTed to your server.
|
|
161
|
+
4. On `200 OK` — the record is marked synced, then kept/deleted based on `onSyncSuccess`.
|
|
162
|
+
5. On `5xx` — retried up to 5 times with exponential backoff.
|
|
163
|
+
6. On `4xx` — marked `failed`, never retried. Fires `onAuthError` on 401/403.
|
|
164
|
+
7. Everything persists across app restarts — the queue survives crashes.
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## Stored Record Shape
|
|
202
169
|
|
|
203
|
-
|
|
170
|
+
Every saved record gets these fields added automatically:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
{
|
|
174
|
+
_id: string // uuid v4
|
|
175
|
+
_ts: number // Date.now() at save time
|
|
176
|
+
_synced: 'pending' | 'synced' | 'failed'
|
|
177
|
+
_type: string // from save() options.type, or ''
|
|
178
|
+
_retries: number // sync attempt count
|
|
179
|
+
|
|
180
|
+
...yourData // everything you passed to save()
|
|
181
|
+
}
|
|
182
|
+
```
|
|
204
183
|
|
|
205
|
-
|
|
206
|
-
- `asyncstorage::__queue__` — Sync queue
|
|
184
|
+
---
|
|
207
185
|
|
|
208
186
|
## Limits
|
|
209
187
|
|
|
210
|
-
|
|
211
|
-
|
|
188
|
+
- Max 5 sync retries per record
|
|
189
|
+
- Not a full database — designed for queuing records, not complex queries
|
|
190
|
+
- Config is locked after `initSyncQueue()` is called
|
|
212
191
|
|
|
213
192
|
## Production Checklist
|
|
214
193
|
|
|
215
|
-
- [ ] Use `payloadTransformer` to
|
|
216
|
-
- [ ] Handle `onAuthError`
|
|
217
|
-
- [ ]
|
|
218
|
-
- [ ]
|
|
219
|
-
- [ ] Call `deleteCollection()` on logout
|
|
220
|
-
- [ ] Monitor queue with `getQueue()` for ops metrics
|
|
194
|
+
- [ ] Use `payloadTransformer` to strip `_` fields before they reach your server
|
|
195
|
+
- [ ] Handle `onAuthError` to catch expired tokens
|
|
196
|
+
- [ ] Call `deleteCollection()` on logout to clear user data
|
|
197
|
+
- [ ] Set `autoSyncCollections` to limit which collections sync automatically
|
package/package.json
CHANGED