wallet-core/src/query.ts

840 lines
22 KiB
TypeScript
Raw Normal View History

/*
This file is part of TALER
2016-01-05 14:20:13 +01:00
(C) 2016 GNUnet e.V.
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
2016-07-07 17:59:29 +02:00
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
2016-01-05 14:20:13 +01:00
/**
* Database query abstractions.
* @module Query
* @author Florian Dold
*/
2017-05-28 01:10:54 +02:00
/**
* Result of an inner join.
*/
export interface JoinResult<L, R> {
2016-10-19 18:40:29 +02:00
left: L;
right: R;
}
2017-05-28 01:10:54 +02:00
/**
* Result of a left outer join.
*/
export interface JoinLeftResult<L, R> {
left: L;
right?: R;
}
2016-10-19 18:40:29 +02:00
2017-05-28 01:10:54 +02:00
/**
* Definition of an object store.
*/
2016-10-18 01:16:31 +02:00
export class Store<T> {
2017-05-28 01:10:54 +02:00
constructor(public name: string,
public storeParams?: IDBObjectStoreParameters,
public validator?: (v: T) => T) {
2016-10-18 01:16:31 +02:00
}
}
2017-05-28 01:10:54 +02:00
/**
* Definition of an index.
*/
export class Index<S extends IDBValidKey, T> {
/**
* Name of the store that this index is associated with.
*/
2016-10-18 01:36:47 +02:00
storeName: string;
2017-05-28 01:10:54 +02:00
constructor(s: Store<T>, public indexName: string, public keyPath: string | string[]) {
2016-10-18 01:36:47 +02:00
this.storeName = s.name;
}
/**
* We want to have the key type parameter in use somewhere,
* because otherwise the compiler complains. In iterIndex the
* key type is pretty useful.
*/
protected _dummyKey: S|undefined;
2016-10-18 01:36:47 +02:00
}
2016-01-11 02:56:32 +01:00
/**
* Stream that can be filtered, reduced or joined
* with indices.
*/
export interface QueryStream<T> {
2017-05-28 01:10:54 +02:00
/**
* Join the current query with values from an index.
* The left side of the join is extracted via a function from the stream's
* result, the right side of the join is the key of the index.
*/
indexJoin<S, I extends IDBValidKey>(index: Index<I, S>, keyFn: (obj: T) => I): QueryStream<JoinResult<T, S>>;
/**
* Join the current query with values from an index, and keep values in the
* current stream that don't have a match. The left side of the join is
* extracted via a function from the stream's result, the right side of the
* join is the key of the index.
*/
indexJoinLeft<S, I extends IDBValidKey>(index: Index<I, S>,
keyFn: (obj: T) => I): QueryStream<JoinLeftResult<T, S>>;
/**
* Join the current query with values from another object store.
* The left side of the join is extracted via a function over the current query,
* the right side of the join is the key of the object store.
*/
keyJoin<S, I extends IDBValidKey>(store: Store<S>, keyFn: (obj: T) => I): QueryStream<JoinResult<T, S>>;
/**
* Only keep elements in the result stream for which the predicate returns
* true.
*/
filter(f: (x: T) => boolean): QueryStream<T>;
/**
* Reduce the stream, resulting in a single value.
*/
reduce<S>(f: (v: T, acc: S) => S, start?: S): Promise<S>;
2017-05-28 01:10:54 +02:00
/**
* Map each element of the stream using a function, resulting in another
* stream of a different type.
*/
map<S>(f: (x: T) => S): QueryStream<S>;
/**
* Map each element of the stream to a potentially empty array, and collect
* the result in a stream of the flattened arrays.
*/
2016-10-19 23:55:58 +02:00
flatMap<S>(f: (x: T) => S[]): QueryStream<S>;
2017-05-28 01:10:54 +02:00
/**
* Collect the stream into an array and return a promise for it.
*/
2016-10-12 02:55:53 +02:00
toArray(): Promise<T[]>;
2017-05-28 01:10:54 +02:00
/**
* Get the first value of the stream.
*/
first(): QueryValue<T>;
2016-10-20 01:37:00 +02:00
/**
* Run the query without returning a result.
* Useful for queries with side effects.
*/
run(): Promise<void>;
2016-01-11 02:56:32 +01:00
}
2016-01-05 14:20:13 +01:00
/**
* Query result that consists of at most one value.
*/
export interface QueryValue<T> {
/**
* Apply a function to a query value.
*/
map<S>(f: (x: T) => S): QueryValue<S>;
/**
* Conditionally execute either of two queries based
* on a property of this query value.
*
* Useful to properly implement complex queries within a transaction (as
* opposed to just computing the conditional and then executing either
* branch). This is necessary since IndexedDB does not allow long-lived
* transactions.
*/
cond<R>(f: (x: T) => boolean, onTrue: (r: QueryRoot) => R, onFalse: (r: QueryRoot) => R): Promise<void>;
}
abstract class BaseQueryValue<T> implements QueryValue<T> {
constructor(public root: QueryRoot) {
}
map<S>(f: (x: T) => S): QueryValue<S> {
2017-05-28 01:10:54 +02:00
return new MapQueryValue<T, S>(this, f);
}
cond<R>(f: (x: T) => boolean, onTrue: (r: QueryRoot) => R, onFalse: (r: QueryRoot) => R): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.subscribeOne((v, tx) => {
if (f(v)) {
onTrue(new QueryRoot(this.root.db));
} else {
onFalse(new QueryRoot(this.root.db));
}
});
resolve();
});
}
abstract subscribeOne(f: SubscribeOneFn): void;
}
class FirstQueryValue<T> extends BaseQueryValue<T> {
private gotValue = false;
private s: QueryStreamBase<T>;
constructor(stream: QueryStreamBase<T>) {
super(stream.root);
this.s = stream;
}
subscribeOne(f: SubscribeOneFn): void {
this.s.subscribe((isDone, value, tx) => {
if (this.gotValue) {
return;
}
if (isDone) {
f(undefined, tx);
} else {
f(value, tx);
}
this.gotValue = true;
});
}
}
2017-05-28 01:10:54 +02:00
class MapQueryValue<T, S> extends BaseQueryValue<S> {
constructor(private v: BaseQueryValue<T>, private mapFn: (x: T) => S) {
super(v.root);
}
subscribeOne(f: SubscribeOneFn): void {
this.v.subscribeOne((v, tx) => this.mapFn(v));
}
}
2017-05-28 01:10:54 +02:00
/**
* Exception that should be thrown by client code to abort a transaction.
*/
export const AbortTransaction = Symbol("abort_transaction");
2016-01-11 02:56:32 +01:00
/**
* Get an unresolved promise together with its extracted resolve / reject
* function.
*/
export function openPromise<T>(): any {
let resolve: ((x?: any) => void) | null = null;
2016-09-12 17:41:12 +02:00
let reject: ((reason?: any) => void) | null = null;
2016-01-11 02:56:32 +01:00
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
2016-09-12 17:41:12 +02:00
if (!(resolve && reject)) {
// Never happens, unless JS implementation is broken
throw Error();
}
2016-10-18 01:36:47 +02:00
return {resolve, reject, promise};
2016-01-11 02:56:32 +01:00
}
abstract class QueryStreamBase<T> implements QueryStream<T> {
2016-01-11 02:56:32 +01:00
abstract subscribe(f: (isDone: boolean,
2016-10-18 01:36:47 +02:00
value: any,
tx: IDBTransaction) => void): void;
constructor(public root: QueryRoot) {
}
2016-01-05 14:20:13 +01:00
first(): QueryValue<T> {
return new FirstQueryValue(this);
}
2016-10-20 01:37:00 +02:00
flatMap<S>(f: (x: T) => S[]): QueryStream<S> {
2017-05-28 01:10:54 +02:00
return new QueryStreamFlatMap<T, S>(this, f);
}
2016-10-20 01:37:00 +02:00
map<S>(f: (x: T) => S): QueryStream<S> {
2016-10-19 23:55:58 +02:00
return new QueryStreamMap(this, f);
}
2017-05-28 01:10:54 +02:00
indexJoin<S, I extends IDBValidKey>(index: Index<I, S>,
keyFn: (obj: T) => I): QueryStream<JoinResult<T, S>> {
2016-10-18 01:36:47 +02:00
this.root.addStoreAccess(index.storeName, false);
return new QueryStreamIndexJoin<T, S>(this, index.storeName, index.indexName, keyFn);
2016-01-05 14:20:13 +01:00
}
2017-05-28 01:10:54 +02:00
indexJoinLeft<S, I extends IDBValidKey>(index: Index<I, S>,
keyFn: (obj: T) => I): QueryStream<JoinLeftResult<T, S>> {
this.root.addStoreAccess(index.storeName, false);
return new QueryStreamIndexJoinLeft<T, S>(this, index.storeName, index.indexName, keyFn);
}
2016-10-19 18:40:29 +02:00
keyJoin<S, I extends IDBValidKey>(store: Store<S>,
keyFn: (obj: T) => I): QueryStream<JoinResult<T, S>> {
this.root.addStoreAccess(store.name, false);
return new QueryStreamKeyJoin<T, S>(this, store.name, keyFn);
}
2016-09-12 17:41:12 +02:00
filter(f: (x: any) => boolean): QueryStream<T> {
2016-01-05 14:20:13 +01:00
return new QueryStreamFilter(this, f);
}
2016-01-05 14:20:13 +01:00
2016-10-12 02:55:53 +02:00
toArray(): Promise<T[]> {
2017-05-28 01:10:54 +02:00
const {resolve, promise} = openPromise();
const values: T[] = [];
2016-10-12 02:55:53 +02:00
this.subscribe((isDone, value) => {
if (isDone) {
resolve(values);
return;
}
values.push(value);
});
return Promise.resolve()
2016-10-18 01:36:47 +02:00
.then(() => this.root.finish())
.then(() => promise);
2016-10-12 02:55:53 +02:00
}
2016-09-12 17:41:12 +02:00
reduce<A>(f: (x: any, acc?: A) => A, init?: A): Promise<any> {
2017-05-28 01:10:54 +02:00
const {resolve, promise} = openPromise();
2016-09-12 17:41:12 +02:00
let acc = init;
2016-01-05 14:20:13 +01:00
this.subscribe((isDone, value) => {
if (isDone) {
2016-09-12 17:41:12 +02:00
resolve(acc);
2016-01-05 14:20:13 +01:00
return;
}
acc = f(value, acc);
});
2016-01-11 02:56:32 +01:00
return Promise.resolve()
2016-10-18 01:36:47 +02:00
.then(() => this.root.finish())
.then(() => promise);
2016-01-05 14:20:13 +01:00
}
run(): Promise<void> {
const {resolve, promise} = openPromise();
this.subscribe((isDone, value) => {
if (isDone) {
resolve();
return;
}
});
return Promise.resolve()
.then(() => this.root.finish())
.then(() => promise);
}
2016-01-05 14:20:13 +01:00
}
2016-09-12 17:41:12 +02:00
type FilterFn = (e: any) => boolean;
type SubscribeFn = (done: boolean, value: any, tx: IDBTransaction) => void;
type SubscribeOneFn = (value: any, tx: IDBTransaction) => void;
2016-01-05 14:20:13 +01:00
2016-01-11 02:56:32 +01:00
class QueryStreamFilter<T> extends QueryStreamBase<T> {
constructor(public s: QueryStreamBase<T>, public filterFn: FilterFn) {
2016-01-05 14:20:13 +01:00
super(s.root);
}
2016-09-12 17:41:12 +02:00
subscribe(f: SubscribeFn) {
2016-01-11 02:56:32 +01:00
this.s.subscribe((isDone, value, tx) => {
2016-01-05 14:20:13 +01:00
if (isDone) {
2016-01-11 02:56:32 +01:00
f(true, undefined, tx);
2016-01-05 14:20:13 +01:00
return;
}
if (this.filterFn(value)) {
f(false, value, tx);
}
});
}
}
2017-05-28 01:10:54 +02:00
class QueryStreamFlatMap<T, S> extends QueryStreamBase<S> {
constructor(public s: QueryStreamBase<T>, public flatMapFn: (v: T) => S[]) {
super(s.root);
}
2016-09-12 17:41:12 +02:00
subscribe(f: SubscribeFn) {
this.s.subscribe((isDone, value, tx) => {
if (isDone) {
f(true, undefined, tx);
return;
}
2017-05-28 01:10:54 +02:00
const values = this.flatMapFn(value);
for (const v in values) {
f(false, v, tx);
2016-01-05 14:20:13 +01:00
}
});
}
}
2017-05-28 01:10:54 +02:00
class QueryStreamMap<S, T> extends QueryStreamBase<T> {
constructor(public s: QueryStreamBase<S>, public mapFn: (v: S) => T) {
2016-10-19 23:55:58 +02:00
super(s.root);
}
subscribe(f: SubscribeFn) {
this.s.subscribe((isDone, value, tx) => {
if (isDone) {
f(true, undefined, tx);
return;
}
2017-05-28 01:10:54 +02:00
const mappedValue = this.mapFn(value);
2016-10-19 23:55:58 +02:00
f(false, mappedValue, tx);
});
}
}
2016-10-19 20:16:01 +02:00
class QueryStreamIndexJoin<T, S> extends QueryStreamBase<JoinResult<T, S>> {
constructor(public s: QueryStreamBase<T>, public storeName: string, public indexName: string,
public key: any) {
2016-01-05 14:20:13 +01:00
super(s.root);
}
2016-09-12 17:41:12 +02:00
subscribe(f: SubscribeFn) {
2016-01-11 02:56:32 +01:00
this.s.subscribe((isDone, value, tx) => {
2016-01-05 14:20:13 +01:00
if (isDone) {
2016-01-11 02:56:32 +01:00
f(true, undefined, tx);
2016-01-05 14:20:13 +01:00
return;
}
2017-05-28 01:10:54 +02:00
const s = tx.objectStore(this.storeName).index(this.indexName);
const req = s.openCursor(IDBKeyRange.only(this.key(value)));
2016-01-05 14:20:13 +01:00
req.onsuccess = () => {
2017-05-28 01:10:54 +02:00
const cursor = req.result;
2016-01-05 14:20:13 +01:00
if (cursor) {
2016-10-19 20:16:01 +02:00
f(false, {left: value, right: cursor.value}, tx);
2016-01-05 14:20:13 +01:00
cursor.continue();
}
2017-05-28 01:10:54 +02:00
};
});
}
}
class QueryStreamIndexJoinLeft<T, S> extends QueryStreamBase<JoinLeftResult<T, S>> {
constructor(public s: QueryStreamBase<T>, public storeName: string, public indexName: string,
public key: any) {
super(s.root);
}
subscribe(f: SubscribeFn) {
this.s.subscribe((isDone, value, tx) => {
if (isDone) {
f(true, undefined, tx);
return;
}
const s = tx.objectStore(this.storeName).index(this.indexName);
const req = s.openCursor(IDBKeyRange.only(this.key(value)));
let gotMatch = false;
req.onsuccess = () => {
2017-05-28 01:10:54 +02:00
const cursor = req.result;
if (cursor) {
gotMatch = true;
f(false, {left: value, right: cursor.value}, tx);
cursor.continue();
2016-01-05 14:20:13 +01:00
} else {
if (!gotMatch) {
f(false, {left: value}, tx);
}
2016-01-05 14:20:13 +01:00
}
2017-05-28 01:10:54 +02:00
};
2016-01-05 14:20:13 +01:00
});
}
}
2016-10-19 18:40:29 +02:00
class QueryStreamKeyJoin<T, S> extends QueryStreamBase<JoinResult<T, S>> {
constructor(public s: QueryStreamBase<T>, public storeName: string,
public key: any) {
2016-10-19 18:40:29 +02:00
super(s.root);
}
subscribe(f: SubscribeFn) {
this.s.subscribe((isDone, value, tx) => {
if (isDone) {
f(true, undefined, tx);
return;
}
2017-05-28 01:10:54 +02:00
const s = tx.objectStore(this.storeName);
const req = s.openCursor(IDBKeyRange.only(this.key(value)));
2016-10-19 18:40:29 +02:00
req.onsuccess = () => {
2017-05-28 01:10:54 +02:00
const cursor = req.result;
2016-10-19 18:40:29 +02:00
if (cursor) {
2017-05-28 01:10:54 +02:00
f(false, {left: value, right: cursor.value}, tx);
2016-10-19 18:40:29 +02:00
cursor.continue();
} else {
f(true, undefined, tx);
}
2017-05-28 01:10:54 +02:00
};
2016-10-19 18:40:29 +02:00
});
}
}
2016-01-11 02:56:32 +01:00
class IterQueryStream<T> extends QueryStreamBase<T> {
2016-09-12 17:41:12 +02:00
private storeName: string;
private options: any;
private subscribers: SubscribeFn[];
2016-01-05 14:20:13 +01:00
2016-09-12 17:41:12 +02:00
constructor(qr: QueryRoot, storeName: string, options: any) {
2016-01-05 14:20:13 +01:00
super(qr);
this.options = options;
this.storeName = storeName;
this.subscribers = [];
2016-01-05 14:20:13 +01:00
2017-05-28 01:10:54 +02:00
const doIt = (tx: IDBTransaction) => {
const {indexName = void 0, only = void 0} = this.options;
2016-09-12 17:41:12 +02:00
let s: any;
if (indexName !== void 0) {
2016-01-11 02:56:32 +01:00
s = tx.objectStore(this.storeName)
2016-10-18 01:36:47 +02:00
.index(this.options.indexName);
2016-01-05 17:11:01 +01:00
} else {
2016-01-11 02:56:32 +01:00
s = tx.objectStore(this.storeName);
2016-01-05 17:11:01 +01:00
}
2017-05-28 01:10:54 +02:00
let kr: IDBKeyRange | undefined;
2016-09-12 17:41:12 +02:00
if (only !== undefined) {
2016-01-05 14:20:13 +01:00
kr = IDBKeyRange.only(this.options.only);
}
2017-05-28 01:10:54 +02:00
const req = s.openCursor(kr);
2016-09-12 17:41:12 +02:00
req.onsuccess = () => {
2017-05-28 01:10:54 +02:00
const cursor: IDBCursorWithValue = req.result;
if (cursor) {
2017-05-28 01:10:54 +02:00
for (const f of this.subscribers) {
f(false, cursor.value, tx);
}
cursor.continue();
} else {
2017-05-28 01:10:54 +02:00
for (const f of this.subscribers) {
f(true, undefined, tx);
}
}
2017-05-28 01:10:54 +02:00
};
2016-01-11 02:56:32 +01:00
};
2016-01-05 17:11:01 +01:00
2016-09-12 17:41:12 +02:00
this.root.addWork(doIt);
}
2016-09-12 17:41:12 +02:00
subscribe(f: SubscribeFn) {
this.subscribers.push(f);
}
}
2017-05-28 22:31:54 +02:00
/**
* Root wrapper around an IndexedDB for queries with a fluent interface.
*/
export class QueryRoot {
2017-05-28 01:10:54 +02:00
private work: Array<((t: IDBTransaction) => void)> = [];
2016-01-11 02:56:32 +01:00
private stores = new Set();
2016-09-12 17:41:12 +02:00
private kickoffPromise: Promise<void>;
2016-01-11 02:56:32 +01:00
/**
* Some operations is a write operation,
* and we need to do a "readwrite" transaction/
*/
2016-09-12 17:41:12 +02:00
private hasWrite: boolean;
2016-10-20 01:37:00 +02:00
private finishScheduled: boolean;
private finished: boolean = false;
2017-05-28 01:10:54 +02:00
constructor(public db: IDBDatabase) {
}
2017-05-28 01:10:54 +02:00
private checkFinished() {
if (this.finished) {
throw Error("Can't add work to query after it was started");
}
}
2017-05-28 01:10:54 +02:00
/**
* Get a stream of all objects in the store.
*/
2016-10-18 01:36:47 +02:00
iter<T>(store: Store<T>): QueryStream<T> {
this.checkFinished();
2016-10-18 01:16:31 +02:00
this.stores.add(store.name);
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
return new IterQueryStream<T>(this, store.name, {});
2016-10-18 01:36:47 +02:00
}
2017-05-28 01:10:54 +02:00
/**
* Count the number of objects in a store.
*/
2016-11-18 04:09:04 +01:00
count<T>(store: Store<T>): Promise<number> {
this.checkFinished();
2016-11-18 04:09:04 +01:00
const {resolve, promise} = openPromise();
const doCount = (tx: IDBTransaction) => {
const s = tx.objectStore(store.name);
const req = s.count();
req.onsuccess = () => {
resolve(req.result);
};
2017-05-28 01:10:54 +02:00
};
2016-11-18 04:09:04 +01:00
this.addWork(doCount, store.name, false);
return Promise.resolve()
.then(() => this.finish())
.then(() => promise);
}
2017-05-28 01:10:54 +02:00
/**
* Delete all objects in a store that match a predicate.
*/
2016-11-18 04:09:04 +01:00
deleteIf<T>(store: Store<T>, predicate: (x: T, n: number) => boolean): QueryRoot {
this.checkFinished();
2016-11-18 04:09:04 +01:00
const doDeleteIf = (tx: IDBTransaction) => {
const s = tx.objectStore(store.name);
const req = s.openCursor();
let n = 0;
req.onsuccess = () => {
2017-05-28 01:10:54 +02:00
const cursor: IDBCursorWithValue = req.result;
2016-11-18 04:09:04 +01:00
if (cursor) {
if (predicate(cursor.value, n++)) {
cursor.delete();
}
cursor.continue();
2017-05-28 01:10:54 +02:00
}
};
2016-11-18 04:09:04 +01:00
};
this.addWork(doDeleteIf, store.name, true);
return this;
}
2017-05-28 01:10:54 +02:00
iterIndex<S extends IDBValidKey, T>(index: Index<S, T>,
only?: S): QueryStream<T> {
this.checkFinished();
2016-10-18 01:36:47 +02:00
this.stores.add(index.storeName);
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
return new IterQueryStream<T>(this, index.storeName, {
2017-05-28 01:10:54 +02:00
indexName: index.indexName,
2016-10-18 01:36:47 +02:00
only,
});
2016-01-05 14:20:13 +01:00
}
2016-01-11 02:56:32 +01:00
/**
* Put an object into the given object store.
* Overrides if an existing object with the same key exists
* in the store.
*/
2016-10-18 01:16:31 +02:00
put<T>(store: Store<T>, val: T): QueryRoot {
this.checkFinished();
2017-05-28 01:10:54 +02:00
const doPut = (tx: IDBTransaction) => {
2016-10-18 01:16:31 +02:00
tx.objectStore(store.name).put(val);
2016-01-11 02:56:32 +01:00
};
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
2016-10-18 01:16:31 +02:00
this.addWork(doPut, store.name, true);
return this;
}
2016-01-11 02:56:32 +01:00
2016-11-13 10:17:39 +01:00
putWithResult<T>(store: Store<T>, val: T): Promise<IDBValidKey> {
this.checkFinished();
2016-11-13 10:17:39 +01:00
const {resolve, promise} = openPromise();
2017-05-28 01:10:54 +02:00
const doPutWithResult = (tx: IDBTransaction) => {
const req = tx.objectStore(store.name).put(val);
2016-11-13 10:17:39 +01:00
req.onsuccess = () => {
resolve(req.result);
2017-05-28 01:10:54 +02:00
};
2016-11-13 10:17:39 +01:00
this.scheduleFinish();
};
this.addWork(doPutWithResult, store.name, true);
return Promise.resolve()
.then(() => this.finish())
.then(() => promise);
}
2017-05-28 01:10:54 +02:00
/**
* Get, modify and store an element inside a transaction.
*/
2016-10-19 18:40:29 +02:00
mutate<T>(store: Store<T>, key: any, f: (v: T) => T): QueryRoot {
this.checkFinished();
2017-05-28 01:10:54 +02:00
const doPut = (tx: IDBTransaction) => {
const reqGet = tx.objectStore(store.name).get(key);
2016-10-19 18:40:29 +02:00
reqGet.onsuccess = () => {
2017-05-28 01:10:54 +02:00
const r = reqGet.result;
2016-10-19 18:40:29 +02:00
let m: T;
try {
m = f(r);
} catch (e) {
2017-05-28 01:10:54 +02:00
if (e === AbortTransaction) {
2016-10-19 18:40:29 +02:00
tx.abort();
return;
}
throw e;
}
tx.objectStore(store.name).put(m);
2017-05-28 01:10:54 +02:00
};
2016-10-19 18:40:29 +02:00
};
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
2016-10-19 18:40:29 +02:00
this.addWork(doPut, store.name, true);
return this;
}
2016-01-11 02:56:32 +01:00
/**
* Add all object from an iterable to the given object store.
* Fails if the object's key is already present
* in the object store.
*/
2016-10-18 01:16:31 +02:00
putAll<T>(store: Store<T>, iterable: T[]): QueryRoot {
this.checkFinished();
2016-01-11 02:56:32 +01:00
const doPutAll = (tx: IDBTransaction) => {
2017-05-28 01:10:54 +02:00
for (const obj of iterable) {
2016-10-18 01:16:31 +02:00
tx.objectStore(store.name).put(obj);
}
2016-01-11 02:56:32 +01:00
};
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
2016-10-18 01:16:31 +02:00
this.addWork(doPutAll, store.name, true);
return this;
}
2016-01-11 02:56:32 +01:00
/**
* Add an object to the given object store.
* Fails if the object's key is already present
* in the object store.
*/
2016-10-18 01:16:31 +02:00
add<T>(store: Store<T>, val: T): QueryRoot {
this.checkFinished();
2016-01-11 02:56:32 +01:00
const doAdd = (tx: IDBTransaction) => {
2016-10-18 01:16:31 +02:00
tx.objectStore(store.name).add(val);
2016-01-11 02:56:32 +01:00
};
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
2016-10-18 01:16:31 +02:00
this.addWork(doAdd, store.name, true);
return this;
}
2016-01-11 02:56:32 +01:00
/**
* Get one object from a store by its key.
*/
2016-10-18 01:16:31 +02:00
get<T>(store: Store<T>, key: any): Promise<T|undefined> {
this.checkFinished();
2016-02-09 21:56:06 +01:00
if (key === void 0) {
throw Error("key must not be undefined");
}
2016-01-11 02:56:32 +01:00
const {resolve, promise} = openPromise();
2016-09-12 17:41:12 +02:00
const doGet = (tx: IDBTransaction) => {
2016-10-18 01:16:31 +02:00
const req = tx.objectStore(store.name).get(key);
2016-09-12 17:41:12 +02:00
req.onsuccess = () => {
2016-01-11 02:56:32 +01:00
resolve(req.result);
};
2016-01-11 02:56:32 +01:00
};
2016-01-05 17:11:01 +01:00
2016-10-18 01:16:31 +02:00
this.addWork(doGet, store.name, false);
2016-01-11 02:56:32 +01:00
return Promise.resolve()
2016-10-18 01:36:47 +02:00
.then(() => this.finish())
.then(() => promise);
}
2016-02-23 14:07:53 +01:00
/**
* Get one object from a store by its key.
*/
2017-05-28 01:10:54 +02:00
getIndexed<I extends IDBValidKey, T>(index: Index<I, T>,
key: I): Promise<T|undefined> {
this.checkFinished();
2016-02-23 14:07:53 +01:00
if (key === void 0) {
throw Error("key must not be undefined");
}
const {resolve, promise} = openPromise<void>();
2016-02-23 14:07:53 +01:00
2016-09-12 17:41:12 +02:00
const doGetIndexed = (tx: IDBTransaction) => {
2016-10-19 18:40:29 +02:00
const req = tx.objectStore(index.storeName)
.index(index.indexName)
.get(key);
2016-09-12 17:41:12 +02:00
req.onsuccess = () => {
2016-02-23 14:07:53 +01:00
resolve(req.result);
};
};
2016-10-18 01:47:40 +02:00
this.addWork(doGetIndexed, index.storeName, false);
2016-02-23 14:07:53 +01:00
return Promise.resolve()
2016-10-18 01:36:47 +02:00
.then(() => this.finish())
.then(() => promise);
2016-02-23 14:07:53 +01:00
}
2016-10-20 01:37:00 +02:00
private scheduleFinish() {
if (!this.finishScheduled) {
Promise.resolve().then(() => this.finish());
this.finishScheduled = true;
}
}
2016-01-11 02:56:32 +01:00
/**
* Finish the query, and start the query in the first place if necessary.
*/
finish(): Promise<void> {
if (this.kickoffPromise) {
return this.kickoffPromise;
}
2016-09-12 17:41:12 +02:00
this.kickoffPromise = new Promise<void>((resolve, reject) => {
// At this point, we can't add any more work
this.finished = true;
2017-05-28 01:10:54 +02:00
if (this.work.length === 0) {
resolve();
return;
}
2016-01-11 02:56:32 +01:00
const mode = this.hasWrite ? "readwrite" : "readonly";
const tx = this.db.transaction(Array.from(this.stores), mode);
tx.oncomplete = () => {
resolve();
};
2016-10-19 18:40:29 +02:00
tx.onabort = () => {
reject(Error("transaction aborted"));
};
2017-05-28 01:10:54 +02:00
for (const w of this.work) {
2016-01-11 02:56:32 +01:00
w(tx);
}
});
return this.kickoffPromise;
}
2016-01-11 02:56:32 +01:00
/**
* Delete an object by from the given object store.
*/
2016-09-12 17:41:12 +02:00
delete(storeName: string, key: any): QueryRoot {
this.checkFinished();
2016-09-12 17:41:12 +02:00
const doDelete = (tx: IDBTransaction) => {
2016-01-11 02:56:32 +01:00
tx.objectStore(storeName).delete(key);
};
2016-10-20 01:37:00 +02:00
this.scheduleFinish();
2016-01-11 02:56:32 +01:00
this.addWork(doDelete, storeName, true);
return this;
}
2016-01-11 02:56:32 +01:00
/**
* Low-level function to add a task to the internal work queue.
*/
2016-09-12 17:41:12 +02:00
addWork(workFn: (t: IDBTransaction) => void,
2016-10-18 01:36:47 +02:00
storeName?: string,
isWrite?: boolean) {
2016-09-12 17:41:12 +02:00
this.work.push(workFn);
if (storeName) {
this.addStoreAccess(storeName, isWrite);
}
}
addStoreAccess(storeName: string, isWrite?: boolean) {
2016-01-11 02:56:32 +01:00
if (storeName) {
this.stores.add(storeName);
}
if (isWrite) {
this.hasWrite = true;
}
}
}