Added database wrapper
All checks were successful
Build / Build NPM Project (push) Successful in 1m7s
Build / Tag Version (push) Successful in 14s
Build / Publish Documentation (push) Successful in 53s

This commit is contained in:
Zakary Timson 2025-05-25 23:02:56 -04:00
parent 97f2bcce2e
commit 6d706d4c15
7 changed files with 126 additions and 138 deletions

View File

@ -1,15 +1,29 @@
<html> <html>
<body> <body>
<script type="module"> <script type="module">
import {Cache, Collection} from './dist/index.mjs'; import {Cache, Database} from './dist/index.mjs';
const db = new Database('test', ['test', 'test2', 'test3']);
const cache = new Cache('id', { const cache = new Cache('id', {
ttl: 60, ttl: 60,
storage: new Collection('test', 'test'), storage: db.table('test'),
expiryPolicy: 'delete' expiryPolicy: 'delete'
}); });
cache.add({id: 1, name: 'zak', age: 27}); const cache2 = new Cache('id', {
ttl: 60,
storage: db.table('test2'),
expiryPolicy: 'delete'
});
const cache3 = new Cache('id', {
ttl: 60,
storage: db.table('test3'),
expiryPolicy: 'delete'
});
console.log(cache3.all());
</script> </script>
</body> </body>
</html> </html>

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.25.2", "version": "0.25.3",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@ -1,11 +1,11 @@
import {Collection} from './collection.ts'; import {Table} from './database.ts';
import {deepCopy, JSONSanitize} from './objects.ts'; import {deepCopy, JSONSanitize} from './objects.ts';
export type CacheOptions = { export type CacheOptions = {
/** Delete keys automatically after x amount of seconds */ /** Delete keys automatically after x amount of seconds */
ttl?: number; ttl?: number;
/** Storage to persist cache */ /** Storage to persist cache */
storage?: Storage | Collection<any, any>; storage?: Storage | Table<any, any>;
/** Key cache will be stored under */ /** Key cache will be stored under */
storageKey?: string; storageKey?: string;
/** Keep or delete cached items once expired, defaults to delete */ /** Keep or delete cached items once expired, defaults to delete */
@ -33,10 +33,11 @@ export class Cache<K extends string | number | symbol, T> {
constructor(public readonly key?: keyof T, public readonly options: CacheOptions = {}) { constructor(public readonly key?: keyof T, public readonly options: CacheOptions = {}) {
if(options.storageKey && !options.storage && typeof(Storage) !== 'undefined') options.storage = localStorage; if(options.storageKey && !options.storage && typeof(Storage) !== 'undefined') options.storage = localStorage;
if(options.storage) { if(options.storage) {
if(options.storage instanceof Collection) { if(options.storage instanceof Table) {
(async () => { (async () => (await options.storage?.getAll()).forEach((v: any) => {
(await options.storage?.getAll()).forEach((v: any) => this.add(v)); console.log(v);
})() this.add(v)
}))()
} else if(options.storageKey) { } else if(options.storageKey) {
const stored = options.storage?.getItem(options.storageKey); const stored = options.storage?.getItem(options.storageKey);
if(stored != null) try { Object.assign(this.store, JSON.parse(stored)); } catch { } if(stored != null) try { Object.assign(this.store, JSON.parse(stored)); } catch { }
@ -62,7 +63,7 @@ export class Cache<K extends string | number | symbol, T> {
private save(key: K) { private save(key: K) {
if(this.options.storage) { if(this.options.storage) {
if(this.options.storage instanceof Collection) { if(this.options.storage instanceof Table) {
this.options.storage.put(key, this.store[key]); this.options.storage.put(key, this.store[key]);
} else if(this.options.storageKey) { } else if(this.options.storageKey) {
this.options.storage.setItem(this.options.storageKey, JSONSanitize(this.store)); this.options.storage.setItem(this.options.storageKey, JSONSanitize(this.store));
@ -138,14 +139,17 @@ export class Cache<K extends string | number | symbol, T> {
*/ */
expire(key: K): this { expire(key: K): this {
this.complete = false; this.complete = false;
if(this.options.expiryPolicy == 'keep') (<any>this.store[key])._expired = true; if(this.options.expiryPolicy == 'keep') {
else this.delete(key); (<any>this.store[key])._expired = true;
this.save(key);
} else this.delete(key);
return this; return this;
} }
/** /**
* Get item from the cache * Get item from the cache
* @param {K} key Key to lookup * @param {K} key Key to lookup
* @param expired Include expired items
* @return {T} Cached item * @return {T} Cached item
*/ */
get(key: K, expired?: boolean): CachedValue<T> | null { get(key: K, expired?: boolean): CachedValue<T> | null {

View File

@ -1,59 +0,0 @@
export class Collection<K extends IDBValidKey, T> {
private database: Promise<IDBDatabase>;
constructor(public readonly db: string, public readonly collection: string, public readonly version?: number, private setup?: (db: IDBDatabase, event: IDBVersionChangeEvent) => void) {
this.database = new Promise((resolve, reject) => {
const req = indexedDB.open(this.db, this.version);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
req.onupgradeneeded = (event) => {
const db = req.result;
if(!db.objectStoreNames.contains(collection)) db.createObjectStore(collection, {keyPath: undefined});
if (this.setup) this.setup(db, event as IDBVersionChangeEvent);
};
});
}
async tx<T>(collection: string, fn: ((store: IDBObjectStore) => IDBRequest), readonly?: boolean): Promise<T> {
const db = await this.database;
const tx = db.transaction(collection, readonly ? 'readonly' : 'readwrite');
const store = tx.objectStore(collection);
return new Promise((resolve, reject) => {
const request = fn(store);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
add(value: T, key?: K): Promise<void> {
return this.tx(this.collection, store => store.add(value, key));
}
count(): Promise<number> {
return this.tx(this.collection, store => store.count(), true);
}
put(key: K, value: T): Promise<void> {
return this.tx(this.collection, store => store.put(value, key));
}
getAll(): Promise<T[]> {
return this.tx(this.collection, store => store.getAll(), true);
}
getAllKeys(): Promise<K[]> {
return this.tx(this.collection, store => store.getAllKeys(), true);
}
get(key: K): Promise<T> {
return this.tx(this.collection, store => store.get(key), true);
}
delete(key: K): Promise<void> {
return this.tx(this.collection, store => store.delete(key));
}
clear(): Promise<void> {
return this.tx(this.collection, store => store.clear());
}
}

94
src/database.ts Normal file
View File

@ -0,0 +1,94 @@
export type TableOptions = {
name: string;
key?: string;
};
export class Database {
connection!: Promise<IDBDatabase>;
constructor(public readonly database: string, public readonly tables: (string | TableOptions)[], public version?: number) {
this.connection = new Promise((resolve, reject) => {
const req = indexedDB.open(this.database, this.version);
req.onerror = () => reject(req.error);
req.onsuccess = () => {
const db = req.result;
if(tables.find(s => !db.objectStoreNames.contains(typeof s === 'string' ? s : s.name))) {
db.close();
Object.assign(this, new Database(this.database, this.tables, db.version + 1));
} else {
this.version = db.version;
resolve(db);
}
};
req.onupgradeneeded = () => {
const db = req.result;
Array.from(db.objectStoreNames)
.filter(s => !this.tables.find(t => typeof t === 'string' ? t : t.name == s))
.forEach(name => db.deleteObjectStore(name));
tables.filter(t => !db.objectStoreNames.contains(typeof t === 'string' ? t : t.name))
.forEach(t => {db.createObjectStore(typeof t === 'string' ? t : t.name, {
keyPath: typeof t === 'string' ? undefined : t.key
});
});
};
});
}
includes(name: string): boolean {
return this.tables.some(t => (typeof t === 'string' ? name === t : name === t.name));
}
table<K extends IDBValidKey = any, T = any>(name: string): Table<K, T> {
return new Table<K, T>(this, name);
}
}
export class Table<K extends IDBValidKey = any, T = any> {
constructor(private readonly database: Database, public readonly name: string) {}
async tx<R>(schema: string, fn: (store: IDBObjectStore) => IDBRequest, readonly = false): Promise<R> {
const db = await this.database.connection;
const tx = db.transaction(schema, readonly ? 'readonly' : 'readwrite');
const store = tx.objectStore(schema);
return new Promise<R>((resolve, reject) => {
const request = fn(store);
request.onsuccess = () => resolve(request.result as R); // ✅ explicit cast
request.onerror = () => reject(request.error);
});
}
add(value: T, key?: K): Promise<void> {
return this.tx(this.name, store => store.add(value, key));
}
count(): Promise<number> {
return this.tx(this.name, store => store.count(), true);
}
put(key: K, value: T): Promise<void> {
return this.tx(this.name, store => store.put(value, key));
}
getAll(): Promise<T[]> {
return this.tx(this.name, store => store.getAll(), true);
}
getAllKeys(): Promise<K[]> {
return this.tx(this.name, store => store.getAllKeys(), true);
}
get(key: K): Promise<T> {
return this.tx(this.name, store => store.get(key), true);
}
delete(key: K): Promise<void> {
return this.tx(this.name, store => store.delete(key));
}
clear(): Promise<void> {
return this.tx(this.name, store => store.clear());
}
}

View File

@ -4,7 +4,7 @@ export * from './aset';
export * from './cache'; export * from './cache';
export * from './color'; export * from './color';
export * from './csv'; export * from './csv';
export * from './collection'; export * from './database';
export * from './files'; export * from './files';
export * from './emitter'; export * from './emitter';
export * from './errors'; export * from './errors';

View File

@ -1,65 +0,0 @@
import {Collection} from '../src';
import 'fake-indexeddb/auto';
describe('IndexedDb and Collection', () => {
const data = {id: 1, name: 'Alice', age: 30, email: '<EMAIL>'};
const data2 = {id: 2, name: 'Bob', age: 39, email: '<EMAIL>'};
let collection = new Collection<number, typeof data>('database', 'collection');
afterEach(() => collection.clear());
test('can set and get an item', async () => {
await collection.put(data.id, data);
const result = await collection.get(data.id);
expect(result).toEqual(data);
});
test('can remove an item', async () => {
await collection.put(data.id, data);
await collection.put(data2.id, data2);
await collection.delete(data.id);
const result = await collection.get(data.id);
const result2 = await collection.get(data2.id);
expect(result).toBeUndefined();
expect(result2).toEqual(data2);
});
test('can clear all items', async () => {
await collection.put(data.id, data);
await collection.put(data2.id, data2);
await collection.clear();
const result = await collection.get(data.id);
const result2 = await collection.get(data2.id);
expect(result).toBeUndefined();
expect(result2).toBeUndefined();
});
test('getItem on missing key returns undefined', async () => {
const result = await collection.get(-1);
expect(result).toBeUndefined();
});
test('count returns number of items', async () => {
expect(await collection.count()).toBe(0);
await collection.put(data.id, data);
expect(await collection.count()).toBe(1);
await collection.delete(data.id);
expect(await collection.count()).toBe(0);
});
test('can get all items', async () => {
await collection.put(data.id, data);
await collection.put(data2.id, data2);
const allItems = await collection.getAll();
expect(allItems).toEqual(expect.arrayContaining([data, data2]));
expect(allItems.length).toBe(2);
});
test('can get all keys', async () => {
await collection.put(data.id, data);
await collection.put(data2.id, data2);
const keys = await collection.getAllKeys();
expect(keys).toEqual(expect.arrayContaining([data.id, data2.id]));
expect(keys.length).toBe(2);
});
});