forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffline-queue.ts
More file actions
206 lines (181 loc) · 4.85 KB
/
Copy pathoffline-queue.ts
File metadata and controls
206 lines (181 loc) · 4.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import AsyncStorage from "@react-native-async-storage/async-storage";
export interface QueuedRequest {
id: string;
url: string;
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
data?: any;
headers?: Record<string, string>;
timestamp: number;
retryCount: number;
maxRetries: number;
}
const QUEUE_KEY = "@offline_queue";
const MAX_RETRIES = 3;
class OfflineQueueManager {
private queue: QueuedRequest[] = [];
private isProcessing = false;
private listeners: (() => void)[] = [];
constructor() {
void this.loadQueue();
}
/**
* Load the queue from persistent storage
*/
private async loadQueue(): Promise<void> {
try {
const stored = await AsyncStorage.getItem(QUEUE_KEY);
if (stored) {
this.queue = JSON.parse(stored);
this.queue = this.queue.filter(
(req) => req.retryCount < req.maxRetries
);
}
} catch (error) {
console.error("Failed to load offline queue:", error);
this.queue = [];
}
}
/**
* Save the queue to persistent storage
*/
private async saveQueue(): Promise<void> {
try {
await AsyncStorage.setItem(QUEUE_KEY, JSON.stringify(this.queue));
} catch (error) {
console.error("Failed to save offline queue:", error);
}
}
/**
* Add a request to the offline queue
*/
async enqueue(
url: string,
method: QueuedRequest["method"],
data?: any,
headers?: Record<string, string>
): Promise<string> {
const id = Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
const request: QueuedRequest = {
id,
url,
method,
data,
headers: headers ?? {},
timestamp: Date.now(),
retryCount: 0,
maxRetries: MAX_RETRIES,
};
this.queue.push(request);
await this.saveQueue();
this.notifyListeners();
return id;
}
/**
* Remove a request from the queue
*/
async dequeue(id: string): Promise<QueuedRequest | undefined> {
const index = this.queue.findIndex((req) => req.id === id);
if (index === -1) return undefined;
const request = this.queue[index];
this.queue.splice(index, 1);
await this.saveQueue();
this.notifyListeners();
return request;
}
/**
* Get all queued requests
*/
getQueue(): QueuedRequest[] {
return [...this.queue];
}
/**
* Get the number of queued requests
*/
getQueueSize(): number {
return this.queue.length;
}
/**
* Clear the queue
*/
async clearQueue(): Promise<void> {
this.queue = [];
await this.saveQueue();
this.notifyListeners();
}
/**
* Process the queue - retry all queued requests
*/
async processQueue(
onSuccess?: (request: QueuedRequest, response: any) => void,
onFailure?: (request: QueuedRequest, error: any) => void
): Promise<void> {
if (this.isProcessing || this.queue.length === 0) return;
this.isProcessing = true;
const toProcess = [...this.queue];
for (const request of toProcess) {
try {
// Skip if already processed or too many retries
if (request.retryCount >= request.maxRetries) {
continue;
}
const response = await this.processRequest(request);
onSuccess?.(request, response);
await this.dequeue(request.id);
} catch (error) {
request.retryCount += 1;
if (request.retryCount >= request.maxRetries) {
onFailure?.(request, error);
await this.dequeue(request.id);
} else {
await this.saveQueue();
}
this.notifyListeners();
}
}
this.isProcessing = false;
this.notifyListeners();
}
private async processRequest(request: QueuedRequest): Promise<any> {
const { url, method, data, headers } = request;
// Build fetch options with proper handling of body
const fetchOptions: RequestInit = {
method,
headers: {
"Content-Type": "application/json",
...headers,
},
};
// Only add body for methods that support it
if (data && method !== "GET" && method !== "DELETE") {
fetchOptions.body = JSON.stringify(data);
}
const response = await fetch(url, fetchOptions);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Handle empty responses
const text = await response.text();
if (!text) {
return null;
}
try {
return JSON.parse(text);
} catch {
return text;
}
}
/**
* Subscribe to queue changes
*/
subscribe(listener: () => void): () => void {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
};
}
private notifyListeners(): void {
this.listeners.forEach((listener) => listener());
}
}
// Export singleton instance
export const offlineQueue = new OfflineQueueManager();