Compare commits

..

9 Commits

Author SHA1 Message Date
e3bbd13ed8 Removed log statement that snuck in
All checks were successful
Build / Build NPM Project (push) Successful in 37s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 37s
2025-06-16 23:37:02 -04:00
1877bac7ce Allow dynamically creating tables
All checks were successful
Build / Build NPM Project (push) Successful in 48s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 42s
2025-06-16 20:56:28 -04:00
c06538a725 Fixed word formatters
All checks were successful
Build / Build NPM Project (push) Successful in 45s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 35s
2025-06-11 18:41:46 -04:00
a08b0c4eea Fixed database init loop
All checks were successful
Build / Build NPM Project (push) Successful in 40s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-05-27 15:42:00 -04:00
1b03ae875b Fixed database includes
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 7s
Build / Publish Documentation (push) Successful in 35s
2025-05-27 15:13:53 -04:00
af1da75a82 Removed console.log statments
All checks were successful
Build / Build NPM Project (push) Successful in 41s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 34s
2025-05-27 14:56:24 -04:00
e19768688d Fixed using numbers as database table name
All checks were successful
Build / Build NPM Project (push) Successful in 1m16s
Build / Tag Version (push) Successful in 15s
Build / Publish Documentation (push) Successful in 53s
2025-05-27 14:51:04 -04:00
6d706d4c15 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
2025-05-25 23:02:56 -04:00
97f2bcce2e removed debugging line
All checks were successful
Build / Build NPM Project (push) Successful in 43s
Build / Tag Version (push) Successful in 8s
Build / Publish Documentation (push) Successful in 36s
2025-05-15 16:47:35 -04:00
7 changed files with 184 additions and 130 deletions

View File

@ -1,15 +1,19 @@
<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 cache = new Cache('id', { const db = new Database('test');
ttl: 60, db.connection.then(() => {
storage: new Collection('test', 'test'), console.log(db.tables);
expiryPolicy: 'delete'
}); });
cache.add({id: 1, name: 'zak', age: 27}); const table = window.table = await db.createTable('test2');
table.add({ name: 'Alice', age: 30 });
table.add({ name: 'Bob', age: 24 });
table.add({ name: 'Carol', age: 30 });
console.log(db.tables);
</script> </script>
</body> </body>
</html> </html>

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.25.1", "version": "0.25.10",
"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 './database.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,8 @@ 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) => this.add(v)))()
(await options.storage?.getAll()).forEach((v: any) => 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 +60,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 +136,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,60 +1,157 @@
export class Collection<K extends IDBValidKey, T> { import {findByProp} from './array.ts';
private database: Promise<IDBDatabase>; import {ASet} from './aset.ts';
export type TableOptions = {
name: string;
key?: string;
autoIncrement?: boolean;
};
export class Database {
connection!: Promise<IDBDatabase>;
ready = false;
tables!: TableOptions[];
constructor(public readonly database: string, tables?: (string | TableOptions)[], public version?: number) {
this.connection = new Promise((resolve, reject) => {
const req = indexedDB.open(this.database, this.version);
this.tables = !tables ? [] : tables.map(t => {
t = typeof t == 'object' ? t : {name: t};
return {...t, name: t.name.toString()};
});
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.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
req.onupgradeneeded = (event) => { req.onsuccess = () => {
const db = req.result; const db = req.result;
if(!db.objectStoreNames.contains(collection)) db.createObjectStore(collection, {keyPath: undefined}); const existing = Array.from(db.objectStoreNames);
if (this.setup) this.setup(db, event as IDBVersionChangeEvent); if(!tables) this.tables = existing.map(t => {
const tx = db.transaction(t, 'readonly', )
const store = tx.objectStore(t);
return {name: t, key: <string>store.keyPath};
});
const desired = new ASet((tables || []).map(t => typeof t == 'string' ? t : t.name));
if(tables && desired.symmetricDifference(new ASet(existing)).length) {
db.close();
Object.assign(this, new Database(this.database, this.tables, db.version + 1));
this.connection.then(resolve);
} else {
this.version = db.version;
resolve(db);
}
this.ready = true;
};
req.onupgradeneeded = () => {
const db = req.result;
const existingTables = new ASet(Array.from(db.objectStoreNames));
if(tables) {
const desired = new ASet((tables || []).map(t => typeof t == 'string' ? t : t.name));
existingTables.difference(desired).forEach(name => db.deleteObjectStore(name));
desired.difference(existingTables).forEach(name => {
const t = this.tables.find(findByProp('name', name));
db.createObjectStore(name, {
keyPath: t?.key,
autoIncrement: t?.autoIncrement || !t?.key
});
});
}
}; };
}); });
} }
async tx<T>(collection: string, fn: ((store: IDBObjectStore) => IDBRequest), readonly?: boolean): Promise<T> { async createTable<K extends IDBValidKey = any, T = any>(table: string | TableOptions): Promise<Table<K, T>> {
const db = await this.database; if(typeof table == 'string') table = {name: table};
const tx = db.transaction(collection, readonly ? 'readonly' : 'readwrite'); const conn = await this.connection;
const store = tx.objectStore(collection); if(!this.includes(table.name)) {
return new Promise((resolve, reject) => { conn.close();
Object.assign(this, new Database(this.database, [...this.tables, table], (this.version ?? 0) + 1));
}
return this.table<K, T>(table.name);
}
async deleteTable(table: string | TableOptions): Promise<void> {
if(typeof table == 'string') table = {name: table};
if(!this.includes(table.name)) return;
const conn = await this.connection;
conn.close();
Object.assign(this, new Database(this.database, this.tables.filter(t => t.name != table.name), (this.version ?? 0) + 1));
}
includes(name: any): boolean {
return !!this.tables.find(t => t.name == (typeof name == 'object' ? name.name : name.toString()));
}
table<K extends IDBValidKey = any, T = any>(name: any): Table<K, T> {
return new Table<K, T>(this, name.toString());
}
}
export class Table<K extends IDBValidKey = any, T = any> {
constructor(private readonly database: Database, public readonly name: string, public readonly key: keyof T | string = 'id') {
this.database.connection.then(() => {
const exists = !!this.database.tables.find(findByProp('name', this.name));
if(!exists) this.database.createTable(this.name);
});
}
async tx<R>(table: string, fn: (store: IDBObjectStore) => IDBRequest, readonly = false): Promise<R> {
const db = await this.database.connection;
const tx = db.transaction(table, readonly ? 'readonly' : 'readwrite');
const store = tx.objectStore(table);
return new Promise<R>((resolve, reject) => {
const request = fn(store); const request = fn(store);
request.onsuccess = () => resolve(request.result); request.onsuccess = () => resolve(request.result as R); // ✅ explicit cast
request.onerror = () => reject(request.error); request.onerror = () => reject(request.error);
}); });
} }
add(value: T, key?: K): Promise<void> { add(value: T, key?: K): Promise<void> {
return this.tx(this.collection, store => store.add(value, key)); return this.tx(this.name, store => store.add(value, key));
}
all = this.getAll;
clear(): Promise<void> {
return this.tx(this.name, store => store.clear());
} }
count(): Promise<number> { count(): Promise<number> {
return this.tx(this.collection, store => store.count(), true); return this.tx(this.name, store => store.count(), true);
} }
put(key: K, value: T): Promise<void> { create = this.add;
debugger;
return this.tx(this.collection, store => store.put(value, key));
}
getAll(): Promise<T[]> { delete(key: K): Promise<void> {
return this.tx(this.collection, store => store.getAll(), true); return this.tx(this.name, store => store.delete(key));
}
getAllKeys(): Promise<K[]> {
return this.tx(this.collection, store => store.getAllKeys(), true);
} }
get(key: K): Promise<T> { get(key: K): Promise<T> {
return this.tx(this.collection, store => store.get(key), true); return this.tx(this.name, store => store.get(key), true);
} }
delete(key: K): Promise<void> { getAll(): Promise<T[]> {
return this.tx(this.collection, store => store.delete(key)); return this.tx(this.name, store => store.getAll(), true);
} }
clear(): Promise<void> { getAllKeys(): Promise<K[]> {
return this.tx(this.collection, store => store.clear()); return this.tx(this.name, store => store.getAllKeys(), true);
} }
put(key: K, value: T): Promise<void> {
return this.tx(this.name, store => store.put(value, key));
}
read(): Promise<T[]>;
read(key: K): Promise<T>;
read(key?: K): Promise<T | T[]> {
return key ? this.get(key) : this.getAll();
}
set(value: T, key?: K): Promise<void> {
if(!key && !(<any>value)[this.key]) return this.add(value);
return this.put(key || (<any>value)[this.key], value);
}
update = this.set;
} }

View File

@ -21,11 +21,13 @@ export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST +
/** /**
* Converts text to camelCase * Converts text to camelCase
*/ */
export function camelCase(str?: string) { export function camelCase(str?: string): string {
const text = pascalCase(str); if(!str) return '';
return !text ? '' : text[0].toLowerCase() + text.slice(1); const pascal = pascalCase(str);
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
} }
/** /**
* Convert number of bytes into a human-readable size * Convert number of bytes into a human-readable size
* *
@ -75,14 +77,12 @@ export function insertAt(target: string, str: string, index: number): String {
/** /**
* Converts text to kebab-case * Converts text to kebab-case
*/ */
export function kebabCase(str: string) { export function kebabCase(str?: string): string {
if(!str) return ''; if(!str) return '';
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '') return wordSegments(str).map(w => w.toLowerCase()).join("-");
.replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `-${args[0].toLowerCase()}`)
.replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}-${args[2]}`)
.replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `-${args[1] ?? ''}`).toLowerCase();
} }
/** /**
* Add padding to string * Add padding to string
* *
@ -112,12 +112,13 @@ export function pad(text: any, length: number, char: string = ' ', start = true)
*/ */
export function pascalCase(str?: string): string { export function pascalCase(str?: string): string {
if(!str) return ''; if(!str) return '';
return str.match(/[a-zA-Z0-9]+/g) return wordSegments(str)
?.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join('') ?? ''; .join('');
} }
/** /**
* Generate a random hexadecimal value * Generate a random hexadecimal value
* *
@ -184,14 +185,12 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
/** /**
* Converts text to snake_case * Converts text to snake_case
*/ */
export function snakeCase(str?: string) { export function snakeCase(str?: string): string {
if(!str) return ''; if(!str) return '';
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '') return wordSegments(str).map(w => w.toLowerCase()).join("_");
.replaceAll(/([A-Z]|[0-9]+)/g, (...args) => `_${args[0].toLowerCase()}`)
.replaceAll(/([0-9])([a-z])/g, (...args) => `${args[1]}_${args[2]}`)
.replaceAll(/[^a-z0-9]+(\w?)/g, (...args) => `_${args[1] ?? ''}`).toLowerCase();
} }
/** /**
* Splice a string together (Similar to Array.splice) * Splice a string together (Similar to Array.splice)
* *
@ -298,6 +297,23 @@ export function md5(d: string) {
function bit_rol(d:any,_:any){return d<<_|d>>>32-_ function bit_rol(d:any,_:any){return d<<_|d>>>32-_
} }
/**
* Splits a string into logical word segments
*/
export function wordSegments(str?: string): string[] {
if (!str) return [];
return str
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
.replace(/([0-9]+)([a-zA-Z])/g, "$1 $2")
.replace(/([a-zA-Z])([0-9]+)/g, "$1 $2")
.replace(/[_\-\s]+/g, " ")
.trim()
.split(/\s+/)
.filter(Boolean);
}
/** /**
* Check if email is valid * Check if email is valid
* *

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);
});
});

View File

@ -59,7 +59,8 @@ describe('String Utilities', () => {
describe('kebabCase', () => { describe('kebabCase', () => {
it('converts to kebab-case', () => { it('converts to kebab-case', () => {
expect(kebabCase('HelloWorldTest')).toContain('-hello'); expect(kebabCase('hello world')).toBe('hello-world');
expect(kebabCase('HelloWorld')).toContain('hello-world');
expect(kebabCase('')).toBe(''); expect(kebabCase('')).toBe('');
}); });
}); });