Browser-side Indexed DB package into a more concise and easy to use interface, database change monitoring!
Technology stack
- RXJS powerful asynchronous management library
demo
import { openIdb, IDbInstall } from "imeepos/idb";
async function bootstrap() {
let update: IDbInstall = {
[` ` 0 to 1]: {
create: [
{
name: "member",
autoIncrement: true,
keyPath: "id",
index: [
{
name: "openid",
keyPath: "openid",
unique: true}]}};let db = await IDB.open("imeepos".1, update, true).toPromise();
// Monitor member table data changes
let obs = db
.readonly("member")
.count(true)
.pipe(distinctUntilChanged())
.subscribe(res= > console.log(res));
let id = 1;
setInterval((a)= > {
/ / insert
db.readwrite("member")
.add({
openid: `fromUser${++id}`
})
.subscribe();
}, 1000);
}
bootstrap();
Copy the code
docs
IDB.open
export class IDB {
static open(
name: string = "imeepos",
version: number = 1, install? : IDbInstall, listen? :boolean
): Observable<IDB>;
}
Copy the code
IDbInstall
// Change the database operation
export type IDBChange = "add" | "delete" | "clear" | "put";
/ / new
interface IdbCreate extends IDBObjectStoreParameters {
name: string;
index: IdbIndex[];
}
/ / index
interface IdbIndex extends IDBIndexParameters {
name: string;
keyPath: string | string[];
}
export interface IDbInstall {
[key: string] : {/ / to addcreate? : IdbCreate[];/ / changeupdate? : { [key:string]: {
create: IdbIndex[];
delete: string[];
};
};
/ / delete
delete? :string[];
};
}
Copy the code
OpenIdbResult
// idb. open Returns the result
export class IDB {
constructor(public db: IDBDatabase, public name: string);
change(tableName: string.type: IDBChange): void;
addListener(tableName, it: any): void;
removeListener(tableName: string, item: any): void;
transaction(
storeNames: string | string[], mode? : IDBTransactionMode): IDBTransaction;
readonly(name: string): IDBReadonly;
index(name: string): IDBIndexed;
readwrite(name: string): IDBReadWrite;
}
Copy the code
IDBReadonly
export interfaceIDBReadonly { count(key? : IDBValidKey | IDBKeyRange): Observable<number>;
get(query: IDBValidKey | IDBKeyRange): Observable<any | undefined>; getAllKeys( query? : IDBValidKey | IDBKeyRange, count? :number
): Observable<IDBValidKey[]>;
getKey(query: IDBValidKey | IDBKeyRange): Observable<IDBValidKey | undefined>; openCursor( range? : IDBValidKey | IDBKeyRange, direction? : IDBCursorDirection ): Observable<IDBCursorWithValue |null>; openKeyCursor( query? : IDBValidKey | IDBKeyRange, direction? : IDBCursorDirection ): Observable<IDBCursor |null>;
}
Copy the code
IDBReadWrite
export interface IDBReadWrite extends IDBReadonly {
add(value: any, key? : IDBValidKey | IDBKeyRange): Observable<IDBValidKey>;delete(key: IDBValidKey | IDBKeyRange): Observable<undefined>;
clear(): Observable<undefined>;
put(value: any, key? : IDBValidKey | IDBKeyRange): Observable<IDBValidKey>; }Copy the code
IDBIndexed
export class IDBIndexed extends IDBReadonly {}
Copy the code