Skip to content
Open
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
50d84ab
chore: upgrade package & replace packaging tools
jin-sir Jun 22, 2025
9131eef
refactor: remove old functions
jin-sir Jun 22, 2025
82a4a25
refactor: rename browserCheck to checkBrowserSupport
jin-sir Jun 22, 2025
9963d6a
refactor: improve copy
jin-sir Jun 22, 2025
5f4b0bd
refactor: rename downLoadData to downloadFile
jin-sir Jun 22, 2025
58a28e5
refactor: rename convertBytes to formatBytes
jin-sir Jun 22, 2025
49bc19b
refactor: rename dateTime to formatDateTime
jin-sir Jun 22, 2025
492de08
feat: add formatSecond
jin-sir Jun 22, 2025
7157840
feat: add formatBase64
jin-sir Jun 22, 2025
bc628b4
refactor: rename generateFullUrlPath to generateUrlWithQuery
jin-sir Jun 22, 2025
ee4e777
refactor: merge generateAKey and getRandomStr into getKey
jin-sir Jun 22, 2025
8530435
refactor: improve getQueryParameters
jin-sir Jun 22, 2025
5cff92d
feat: add getTypeOfValue
jin-sir Jun 22, 2025
56ba7cc
refactor: improve isMacOS
jin-sir Jun 22, 2025
1705964
refactor: improve isMobile
jin-sir Jun 22, 2025
8df8b0e
refactor: improve isWindows
jin-sir Jun 22, 2025
d8eb0bd
refactor: localDB.set support batch set, localDB.clear support except…
jin-sir Jun 22, 2025
d35ca34
refactor: improve LocalIndexedDB
jin-sir Jun 22, 2025
1744d5b
feat: add sessionDB
jin-sir Jun 22, 2025
3166fec
feat: add shouldRender
jin-sir Jun 22, 2025
c20cf9d
refactor: merge getBase64 and base64Encode into toBase64
jin-sir Jun 22, 2025
a2774db
refactor: rename percent to toPercent
jin-sir Jun 22, 2025
4dea50d
refactor: rename exchangeOrder to toSortOrder
jin-sir Jun 22, 2025
20c180a
refactor: rename getThousandth to toThousand
jin-sir Jun 22, 2025
fb7148e
feat: add unit testing
jin-sir Jun 22, 2025
3f9cee2
chore: add entry file
jin-sir Jun 22, 2025
f5e2bf1
chore: remove docs
jin-sir Jun 22, 2025
44587fe
refactor: build site with VitePress and generate documentation using …
jin-sir Jun 22, 2025
2e8f0a5
chore: add docs:deploy script
jin-sir Jun 22, 2025
b766ac0
chore: replace yarn with pnpm
jin-sir Jul 29, 2025
2aa1db3
refactor: rename LocalIndexedDB to IndexedDB
jin-sir Aug 6, 2025
853ef05
refactor: improve code
jin-sir Aug 6, 2025
00c11ed
chore: translate English comments to Chinese
jin-sir Aug 8, 2025
c80bde9
chore: update project configuration and set TypeScript package version
jin-sir Aug 8, 2025
698f9d0
chore: update docs
jin-sir Aug 8, 2025
77ce923
Merge remote-tracking branch 'origin/master' into feat_utils
jin-sir Aug 8, 2025
94aba92
chore: replace yarn with pnpm
jin-sir Aug 8, 2025
fb73a55
refactor: rename getKey to generateUniqueId
jin-sir Aug 22, 2025
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
207 changes: 207 additions & 0 deletions src/localIndexedDB/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/**
* LocalIndexedDB
*
* @deprecated
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

为啥废弃,是因为想要直接用第三方包吗,会影响文档

image image

* @category Storage
* @description
* This class provides a wrapper for IndexedDB, a low-level API for client-side storage of significant amounts of structured data, including files/blobs.
* It allows you to store and retrieve data in a structured format, and to query and manipulate that data using a variety of methods.
*
* @example
* ```typescript
* import { LocalIndexedDB } from 'dt-utils';
*
* // Initialize database
* const db = new LocalIndexedDB('userDB', 1, 'users');
* await db.open();
*
* // Add data
* await db.add('user1', { name: 'John', age: 30 });
*
* // Get data
* const user = await db.get('user1');
*
* // Update data
* await db.set('user1', { name: 'John', age: 31 });
*
* // Delete data
* await db.delete('user1');
*
* // Clear all data
* await db.clear();
* ```
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB|MDN IndexedDB Usage Guide}
* @see {@link https://caniuse.com/#feat=indexeddb|Browser Compatibility}
*/
class LocalIndexedDB {
private _db!: IDBDatabase;
private _version!: number;
private _database!: string;
private _storeName!: string;
private _openLog!: boolean;

/**
* Constructor for a new indexedDB object
* @param database Database name
* @param version Database version
* @param storeName Store object name
* @param openLog Whether to log indexedDB changes
*/
constructor(database: string, version: number, storeName: string, openLog = false) {
if (!this.checkBrowserSupport()) {
console.error("This browser doesn't support IndexedDB");
return;
}
this._storeName = storeName;
this._version = version;
this._database = database;
this._openLog = openLog;
}

private checkBrowserSupport(): boolean {
return 'indexedDB' in window;
}

/**
* Open the database indicated in the constructor function.
* This method returns a Promise that resolves to the db instance.
*/
public async open(): Promise<IDBDatabase> {
if (this._db) {
return this._db;
}

try {
this._db = await this.createConnection();
return this._db;
} catch (error) {
this.log('Failed to open database:', error);
throw error;
}
}

private createConnection(): Promise<IDBDatabase> {
return new Promise<IDBDatabase>((resolve, reject) => {
/**
* If exist the same version database, there need upgrade an new version database,
* because of the same version can't trigger onupgradeneeded event which will occur
* object stores was not found exception.
*/
const request = indexedDB.open(this._database, this._version);

request.onsuccess = () => {
this._db = request.result;
this.setupVersionChangeHandler();
this.log('Open indexedDB success!');
resolve(this._db);
};

request.onupgradeneeded = (event) => {
this._db = request.result;
this.handleUpgrade(event, request, resolve);
};

request.onblocked = (event) => {
this.log('Database open blocked', event);
reject(new Error('Database open blocked'));
};

request.onerror = (event) => {
this.log('Maybe you not allow my web app to use IndexedDB!', event);
reject(event);
};
});
}

private handleUpgrade(
event: IDBVersionChangeEvent,
request: IDBOpenDBRequest,
resolve: (value: IDBDatabase) => void
): void {
if (!this._db.objectStoreNames.contains(this._storeName)) {
const objectStore = this._db.createObjectStore(this._storeName);
objectStore.transaction.oncomplete = () => {
resolve(request.result);
};
}
this.log('Database Upgraded', event);
}

private setupVersionChangeHandler(): void {
this._db.onversionchange = (event) => {
this.log('Database version changed', event);
// Close database connection to avoid blocking upgrade operations in other tabs
this._db.close();
this._db = null as any;
};
}

private createTransactionStore(storeName: string, mode: IDBTransactionMode): IDBObjectStore {
if (!this._db) {
throw new Error('Database not connected, please call open() method first');
}
const transaction = this._db.transaction([storeName], mode);

return transaction.objectStore(storeName);
}

public async add<T>(key: string, value: T): Promise<IDBRequest> {
await this.ensureConnection();
return this.executeStoreOperation((store) => store.add(value, key));
}

public async set<T>(key: string, value: T): Promise<IDBRequest> {
await this.ensureConnection();
this.log('IndexedDB set', key, value);
return this.executeStoreOperation((store) => store.put(value, key));
}

public async get<T>(key: string): Promise<T> {
await this.ensureConnection();
this.log('IndexedDB get', key);
return this.executeStoreOperation<T>((store) => store.get(key));
}

public async delete(key: string): Promise<IDBRequest> {
await this.ensureConnection();
return this.executeStoreOperation((store) => store.delete(key));
}

public async clear(): Promise<IDBRequest> {
await this.ensureConnection();
return this.executeStoreOperation((store) => store.clear());
}

private async ensureConnection(): Promise<void> {
if (!this._db) {
await this.open();
}
}

private executeStoreOperation<T>(operate: (store: IDBObjectStore) => IDBRequest): Promise<T> {
return new Promise((resolve, reject) => {
try {
const store = this.createTransactionStore(this._storeName, 'readwrite');
const request = operate(store);

request.onsuccess = () => resolve(request.result);
request.onerror = (event) => {
this.log('Store operation error:', event);
reject(event);
};
} catch (error) {
this.log('Error during store operation:', error);
reject(error);
}
});
}

private log(...args: any[]): void {
if (this._openLog) {
console.log(`[IndexedDB ${this._database}]`, ...args);
}
}
}

export default LocalIndexedDB;