-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathWatchedQuery.ts
190 lines (158 loc) · 4.59 KB
/
WatchedQuery.ts
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
import {
AbstractPowerSyncDatabase,
BaseListener,
BaseObserver,
CompilableQuery,
Disposable,
runOnSchemaChange
} from '@powersync/common';
import { AdditionalOptions } from './hooks/useQuery';
export class Query<T> {
rawQuery: string | CompilableQuery<T>;
sqlStatement: string;
queryParameters: any[];
}
export interface WatchedQueryListener extends BaseListener {
onUpdate: () => void;
disposed: () => void;
}
export class WatchedQuery extends BaseObserver<WatchedQueryListener> implements Disposable {
readyPromise: Promise<void>;
isReady: boolean = false;
currentData: any[] | undefined;
currentError: any;
tables: any[] | undefined;
private temporaryHolds = new Set();
private controller: AbortController | undefined;
private db: AbstractPowerSyncDatabase;
private resolveReady: undefined | (() => void);
readonly query: Query<unknown>;
readonly options: AdditionalOptions;
constructor(db: AbstractPowerSyncDatabase, query: Query<unknown>, options: AdditionalOptions) {
super();
this.db = db;
this.query = query;
this.options = options;
this.readyPromise = new Promise((resolve) => {
this.resolveReady = resolve;
});
}
addTemporaryHold() {
const ref = new Object();
this.temporaryHolds.add(ref);
this.maybeListen();
let timeout: any;
const release = () => {
this.temporaryHolds.delete(ref);
if (timeout) {
clearTimeout(timeout);
}
this.maybeDispose();
};
const timeoutRelease = () => {
if (this.isReady || this.controller == null) {
release();
} else {
// If the query is taking long, keep the temporary hold.
timeout = setTimeout(timeoutRelease, 5_000);
}
};
timeout = setTimeout(timeoutRelease, 5_000);
return release;
}
registerListener(listener: Partial<WatchedQueryListener>): () => void {
const disposer = super.registerListener(listener);
this.maybeListen();
return () => {
disposer();
this.maybeDispose();
};
}
private async fetchTables() {
try {
this.tables = await this.db.resolveTables(this.query.sqlStatement, this.query.queryParameters, this.options);
} catch (e) {
console.error('Failed to fetch tables:', e);
this.setError(e);
}
}
async fetchData() {
try {
const result =
typeof this.query.rawQuery == 'string'
? await this.db.getAll(this.query.sqlStatement, this.query.queryParameters)
: await this.query.rawQuery.execute();
const data = result ?? [];
this.setData(data);
} catch (e) {
console.error('Failed to fetch data:', e);
this.setError(e);
}
}
private maybeListen() {
if (this.controller != null) {
return;
}
if (this.onUpdateListenersCount() == 0 && this.temporaryHolds.size == 0) {
return;
}
const controller = new AbortController();
this.controller = controller;
const onError = (error: Error) => {
this.setError(error);
};
const watchQuery = async (abortSignal: AbortSignal) => {
await this.fetchTables();
await this.fetchData();
if (!this.options.runQueryOnce) {
this.db.onChangeWithCallback(
{
onChange: async () => {
await this.fetchData();
},
onError
},
{
...this.options,
signal: abortSignal,
tables: this.tables
}
);
}
};
runOnSchemaChange(watchQuery, this.db, { signal: this.controller.signal });
}
private setData(results: any[]) {
this.isReady = true;
this.currentData = results;
this.currentError = undefined;
this.resolveReady?.();
this.iterateListeners((l) => l.onUpdate?.());
}
private setError(error: any) {
this.isReady = true;
this.currentData = undefined;
this.currentError = error;
this.resolveReady?.();
this.iterateListeners((l) => l.onUpdate?.());
}
private onUpdateListenersCount(): number {
return Array.from(this.listeners).filter((listener) => listener.onUpdate !== undefined).length;
}
private maybeDispose() {
if (this.onUpdateListenersCount() == 0 && this.temporaryHolds.size == 0) {
this.controller?.abort();
this.controller = undefined;
this.isReady = false;
this.currentData = undefined;
this.currentError = undefined;
this.dispose();
this.readyPromise = new Promise((resolve, reject) => {
this.resolveReady = resolve;
});
}
}
async dispose() {
this.iterateAsyncListeners(async (l) => l.disposed?.());
}
}