forked from rocicorp/replicache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscan-iterator.ts
More file actions
186 lines (161 loc) · 5.44 KB
/
Copy pathscan-iterator.ts
File metadata and controls
186 lines (161 loc) · 5.44 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
import {Invoke, RPC, ScanRequest} from './repm-invoker.js';
import type {JSONValue} from './json.js';
import {throwIfClosed} from './transaction-closed-error.js';
import {ScanOptions, toRPC} from './scan-options.js';
import {asyncIterableToArray} from './async-iterable-to-array.js';
interface IdCloser {
close(): void;
closed: boolean;
id: number;
}
const VALUE = 0;
const KEY = 1;
const ENTRY = 2;
type ScanIterableKind = typeof VALUE | typeof KEY | typeof ENTRY;
type Args = [
options: ScanOptions | undefined,
invoke: Invoke,
getTransaction: () => Promise<IdCloser> | IdCloser,
shouldCloseTransaction: boolean,
];
/**
* This class is used for the results of [[ReadTransaction.scan|scan]]. It
* implements `AsyncIterable<JSONValue>` which allows you to use it in a `for
* await` loop. There are also methods to iterate over the [[keys]],
* [[entries]] or [[values]].
*/
export class ScanResult<K> implements AsyncIterable<JSONValue> {
private readonly _args: Args;
/** @internal */
constructor(...args: Args) {
this._args = args;
}
/** The default AsyncIterable. This is the same as [[values]]. */
[Symbol.asyncIterator](): AsyncIterableIteratorToArrayWrapper<JSONValue> {
return this.values();
}
/** Async iterator over the valus of the [[ReadTransaction.scan|scan]] call. */
values(): AsyncIterableIteratorToArrayWrapper<JSONValue> {
return new AsyncIterableIteratorToArrayWrapper(this._newIterator(VALUE));
}
/**
* Async iterator over the keys of the [[ReadTransaction.scan|scan]]
* call. If the [[ReadTransaction.scan|scan]] is over an index the key
* is a tuple of `[secondaryKey: string, primaryKey]`
*/
keys(): AsyncIterableIteratorToArrayWrapper<K> {
return new AsyncIterableIteratorToArrayWrapper(this._newIterator(KEY));
}
/**
* Async iterator over the entries of the [[ReadTransaction.scan|scan]]
* call. An entry is a tuple of key values. If the
* [[ReadTransaction.scan|scan]] is over an index the key is a tuple of
* `[secondaryKey: string, primaryKey]`
*/
entries(): AsyncIterableIteratorToArrayWrapper<[K, JSONValue]> {
return new AsyncIterableIteratorToArrayWrapper(this._newIterator(ENTRY));
}
/** Returns all the values as an array. Same as `values().toArray()` */
toArray(): Promise<JSONValue[]> {
return this.values().toArray();
}
private _newIterator<V>(kind: ScanIterableKind): AsyncIterableIterator<V> {
return scanIterator(kind, ...this._args);
}
}
/**
* A class that wraps an async iterable iterator to add a [[toArray]] method.
*
* Usage:
*
* ```ts
* const keys: string[] = await rep.scan().keys().toArray();
* ```
*/
export class AsyncIterableIteratorToArrayWrapper<V>
implements AsyncIterableIterator<V>
{
private readonly _it: AsyncIterableIterator<V>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly next: (v?: any) => Promise<IteratorResult<V>>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly return?: (value?: any) => Promise<IteratorResult<V>>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly throw?: (e?: any) => Promise<IteratorResult<V>>;
constructor(it: AsyncIterableIterator<V>) {
this._it = it;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.next = (v: any) => it.next(v);
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion
this.return = it.return ? (v: any) => it.return!(v) : undefined;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion
this.throw = it.throw ? (v: any) => it.throw!(v) : undefined;
}
toArray(): Promise<V[]> {
return asyncIterableToArray(this._it);
}
[Symbol.asyncIterator](): AsyncIterableIterator<V> {
return this._it[Symbol.asyncIterator]();
}
}
async function* scanIterator<V>(
kind: ScanIterableKind,
options: ScanOptions | undefined,
invoke: Invoke,
getTransaction: () => Promise<IdCloser> | IdCloser,
shouldCloseTransaction: boolean,
): AsyncGenerator<V> {
const transaction = await getTransaction();
throwIfClosed(transaction);
const items = await load<V>(kind, options, transaction.id, invoke);
try {
for (const item of items) {
yield item;
}
} finally {
if (shouldCloseTransaction && !transaction.closed) {
transaction.close();
}
}
}
async function load<V>(
kind: ScanIterableKind,
options: ScanOptions | undefined,
transactionID: number,
invoke: Invoke,
): Promise<V[]> {
const items: V[] = [];
const decoder = new TextDecoder();
const parse = (v: Uint8Array) => JSON.parse(decoder.decode(v));
type MaybeIndexName = {indexName?: string};
const key = (primaryKey: string, secondaryKey: string | null) =>
(options as MaybeIndexName)?.indexName !== undefined
? [secondaryKey, primaryKey]
: primaryKey;
const receiver = (
primaryKey: string,
secondaryKey: string | null,
value: Uint8Array,
) => {
switch (kind) {
case VALUE:
items.push(parse(value));
return;
case KEY:
items.push(key(primaryKey, secondaryKey) as unknown as V);
return;
case ENTRY:
items.push([
key(primaryKey, secondaryKey),
parse(value),
] as unknown as V);
}
};
const args: ScanRequest = {
transactionId: transactionID,
opts: toRPC(options),
receiver,
};
await invoke(RPC.Scan, args);
return items;
}