Skip to content
This repository has been archived by the owner on Jul 27, 2020. It is now read-only.

add ability to clear store #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions spec/database.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,29 @@ describe('database functionality', () => {
});
});

it('should clear store', (done) => {
let found;
idb.clear('todos').subscribe(
() => {},
err => {
console.error(err),
done(err);
},
() => {
idb.query('todos').toArray().subscribe(
(records) => {
found = records;
},
err => {
console.error(err);
done(err);
},
() => {
expect(found.length).toEqual(0);
done();
}
);
})
});

});
32 changes: 32 additions & 0 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,38 @@ export class Database {
compare(a: any, b: any): number {
return this._idb.cmp(a, b);
}

clear(storeName: string) {
const open$ = this.open(this._schema.name);
return mergeMap.call(open$, (db: IDBDatabase) => {
return new Observable( (txnObserver: Observer<any>) => {
const recordSchema = this._schema.stores[storeName];
const mapper = this._mapRecord(recordSchema);
const txn = db.transaction([storeName], IDB_TXN_READWRITE);
const objectStore = txn.objectStore(storeName);

const clearRequest = objectStore.clear();

const onTxnError = (err: any) => txnObserver.error(err);
const onTxnComplete = () => txnObserver.complete();
const onClear = () => txnObserver.next(null);

txn.addEventListener(IDB_COMPLETE, onTxnComplete);
txn.addEventListener(IDB_ERROR, onTxnError);

clearRequest.addEventListener(IDB_SUCCESS, onClear);
clearRequest.addEventListener(IDB_ERROR, onTxnError);

return () => {
clearRequest.removeEventListener(IDB_SUCCESS, onClear);
clearRequest.removeEventListener(IDB_ERROR, onTxnError);
txn.removeEventListener(IDB_COMPLETE, onTxnComplete);
txn.removeEventListener(IDB_ERROR, onTxnError);
};

});
});
}
}


Expand Down