indexedDb数据库基本操作

indexedDb数据库基本操作
随便写写
把回调函数改写为Promise异步操作,新增加了分页功能。

export class IndexedDb {
	databasename: string;

	v: number;

	private _openDBRequest!: IDBOpenDBRequest;

	private _instance!: IDBDatabase;

	private _upgradeneeded?: (e: Event) => void;

	constructor(databasename, v = 1, upgradeneeded?: (e: Event) => void) {
		this.databasename = databasename;
		this.v = v;
		this._upgradeneeded = upgradeneeded;
	}

	async instance(): Promise<IDBDatabase> {
		if (!this._instance) {
			this._openDBRequest = window.indexedDB.open(this.databasename, this.v);
			return new Promise((resolve, reject) => {
				this._openDBRequest.onsuccess = (e: any) => {
					resolve(e.target.result);
				};
				this._openDBRequest.onerror = (e: any) => {
					reject(e.target.error);
				};
				this._openDBRequest.onupgradeneeded = (e) => {
					this._upgradeneeded && this._upgradeneeded(e);
				};
			});
		}
		return Promise.resolve(this._instance);
	}
}

export class IndexedDbObjectStore {
	private _indexedDb: IndexedDb;

	private _name: string;

	private _instance!: IDBObjectStore;

	private _mode: "readonly" | "readwrite" | "versionchange";

	constructor(indexedDb: IndexedDb, storename: string, mode: "readonly" | "readwrite" | "versionchange" = "readonly") {
		this._name = storename;
		this._indexedDb = indexedDb;
		this._mode = mode;
	}

	async instance() {
		if (!this._instance) {
			const indexdb = await this._indexedDb.instance();
			this._instance = indexdb.transaction(this._name, this._mode).objectStore(this._name);
		}
		return Promise.resolve(this._instance);
	}

	async add(value: any, key?: string | number | Date): Promise<IDBValidKey> {
		return this._callback((await this.instance()).add(value, key));
	}

	async put(value: any, key?: string | number | Date): Promise<IDBValidKey> {
		return this._callback((await this.instance()).put(value, key));
	}

	async delete(key: string | number | Date) {
		return this._callback((await this.instance()).delete(key));
	}

	async deleteIndex(name: string) {
		(await this.instance()).deleteIndex(name);
	}

	async clear() {
		return this._callback((await this.instance()).clear());
	}

	async get(query: string | number | Date) {
		return this._callback((await this.instance()).get(query));
	}

	async getAll(query?: string | number | Date) {
		return this._callback((await this.instance()).getAll(query));
	}

	async getAllKeys(query?: string | number | Date) {
		return this._callback((await this.instance()).getAllKeys(query));
	}

	async getKey(query: string | number | Date) {
		return this._callback((await this.instance()).getKey(query));
	}

	async index(name: string) {
		return (await this.instance()).index(name);
	}

	async count(key?: string | number | Date) {
		return this._callback((await this.instance()).count(key));
	}

	async pagination(page = 1, rows = 20) {
		const instance = await this.instance();
		let index = page - 1;
		return (data: Array<any>, range?: string | number | Date) => {
			const result = instance.openCursor(range);
			let [state, count] = ["start", 0];
			const start = () => {
				if (result.result) {
					index * rows ? result.result.advance(index * rows) : next();
				}
				index++;
				state = "next";
			};

			const next = () => {
				!result.result || count > rows ? (state = "done") : data.push(result.result.value);
				result.result?.continue();
				count++;
			};

			const done = () => page++;

			const obj = Object.assign({ start, next, done }, {});

			result.onsuccess = (e) => obj[state]();
		};
	}

	private _callback<T>(result: IDBRequest<T>): Promise<T> {
		return new Promise((resolve, reject) => {
			result.onsuccess = function() {
				resolve(this.result);
			};
			result.onerror = function() {
				reject(this.error);
			};
		});
	}
}

export const indexdb = new IndexedDb("indexdatabase", 1, (e: any) => {
	const result = <IDBDatabase>e.target.result;
	result.createObjectStore("sitemaps", { autoIncrement: true, keyPath: "id" });
});

// const store = new IndexedDbObjectStore(indexdb, "sitemaps", "readwrite");
// store.add({ name: 1, sex: "男" });
// store.add({ name: 2, sex: "男" });
// store.add({ name: 3, sex: "妇" });
// store.add({ name: 4, sex: "磊" });

// const data = new Array();

// (async () => {
//     const nextpage = await store.pagination(1, 20);
//     nextpage(data);
//     nextpage(data);
//     nextpage(data);
//     nextpage(data);

//     setTimeout(() => {
//         const d = data.sort(function (a, b) {
//             return a.id - b.id;
//         });
//         console.log(d);
//     }, 2000);

//     //console.log(d);
// })();


原文地址:https://www.cnblogs.com/whnba/p/14359714.html