Compare commits

..

3 Commits

Author SHA1 Message Date
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
5 changed files with 125 additions and 35 deletions

View File

@ -3,7 +3,17 @@
<script type="module">
import {Cache, Database} from './dist/index.mjs';
const db = new Database('test', []);
const db = new Database('test');
db.connection.then(() => {
console.log(db.tables);
});
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>
</body>
</html>

View File

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

View File

@ -1,44 +1,85 @@
import {findByProp} from './array.ts';
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) {
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.map(t => typeof t == 'object' ? t : {name: t});
const tableNames = new ASet(this.tables.map(t => t.name));
this.tables = !tables ? [] : tables.map(t => {
t = typeof t == 'object' ? t : {name: t};
return {...t, name: t.name.toString()};
});
req.onerror = () => reject(req.error);
req.onsuccess = () => {
const db = req.result;
if(tableNames.symmetricDifference(new ASet(Array.from(db.objectStoreNames))).length) {
const existing = Array.from(db.objectStoreNames);
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));
existingTables.difference(tableNames).forEach(name => db.deleteObjectStore(name));
tableNames.difference(existingTables).forEach(name => db.createObjectStore(name));
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 createTable<K extends IDBValidKey = any, T = any>(table: string | TableOptions): Promise<Table<K, T>> {
if(typeof table == 'string') table = {name: table};
const conn = await this.connection;
if(!this.includes(table.name)) {
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 == name.toString());
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> {
@ -47,7 +88,12 @@ export class Database {
}
export class Table<K extends IDBValidKey = any, T = any> {
constructor(private readonly database: Database, public readonly name: string) {}
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;
@ -64,12 +110,24 @@ export class Table<K extends IDBValidKey = any, T = any> {
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> {
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));
create = this.add;
delete(key: K): Promise<void> {
return this.tx(this.name, store => store.delete(key));
}
get(key: K): Promise<T> {
return this.tx(this.name, store => store.get(key), true);
}
getAll(): Promise<T[]> {
@ -80,15 +138,20 @@ export class Table<K extends IDBValidKey = any, T = any> {
return this.tx(this.name, store => store.getAllKeys(), true);
}
get(key: K): Promise<T> {
return this.tx(this.name, store => store.get(key), true);
put(key: K, value: T): Promise<void> {
return this.tx(this.name, store => store.put(value, key));
}
delete(key: K): Promise<void> {
return this.tx(this.name, store => store.delete(key));
read(): Promise<T[]>;
read(key: K): Promise<T>;
read(key?: K): Promise<T | T[]> {
return key ? this.get(key) : this.getAll();
}
clear(): Promise<void> {
return this.tx(this.name, store => store.clear());
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
*/
export function camelCase(str?: string) {
const text = pascalCase(str);
return !text ? '' : text[0].toLowerCase() + text.slice(1);
export function camelCase(str?: string): string {
if(!str) return '';
const pascal = pascalCase(str);
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
}
/**
* 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
*/
export function kebabCase(str: string) {
export function kebabCase(str?: string): string {
if(!str) return '';
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
.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();
return wordSegments(str).map(w => w.toLowerCase()).join("-");
}
/**
* 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 {
if(!str) return '';
return str.match(/[a-zA-Z0-9]+/g)
?.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join('') ?? '';
return wordSegments(str)
.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join('');
}
/**
* Generate a random hexadecimal value
*
@ -184,14 +185,12 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
/**
* Converts text to snake_case
*/
export function snakeCase(str?: string) {
export function snakeCase(str?: string): string {
if(!str) return '';
return str.replaceAll(/(^[^a-zA-Z]+|[^a-zA-Z0-9-_])/g, '')
.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();
return wordSegments(str).map(w => w.toLowerCase()).join("_");
}
/**
* 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-_
}
/**
* 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
*

View File

@ -59,7 +59,8 @@ describe('String Utilities', () => {
describe('kebabCase', () => {
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('');
});
});