Compare commits

..

2 Commits

Author SHA1 Message Date
91dc17667e Better cache & database integration
All checks were successful
Build / Build NPM Project (push) Successful in 44s
Build / Tag Version (push) Successful in 13s
Build / Publish Documentation (push) Successful in 51s
2025-06-20 19:41:01 -04:00
11cfc67650 Added cache find function
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 35s
2025-06-19 19:46:59 -04:00
2 changed files with 19 additions and 3 deletions

View File

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

View File

@ -1,5 +1,5 @@
import {Table} from './database.ts';
import {deepCopy, JSONSanitize} from './objects.ts';
import {deepCopy, includes, JSONSanitize} from './objects.ts';
export type CacheOptions = {
/** Delete keys automatically after x amount of seconds */
@ -34,7 +34,12 @@ export class Cache<K extends string | number | symbol, T> {
if(options.storageKey && !options.storage && typeof(Storage) !== 'undefined') options.storage = localStorage;
if(options.storage) {
if(options.storage instanceof Table) {
(async () => (await options.storage?.getAll()).forEach((v: any) => this.add(v)))()
(async () => (await options.storage?.getAll()).forEach((v: any) => {
if(v) {
try { this.add(v) }
catch { }
}
}))()
} else if(options.storageKey) {
const stored = options.storage?.getItem(options.storageKey);
if(stored != null) try { Object.assign(this.store, JSON.parse(stored)); } catch { }
@ -55,6 +60,7 @@ export class Cache<K extends string | number | symbol, T> {
private getKey(value: T): K {
if(!this.key) throw new Error('No key defined');
if(value[this.key] === undefined) throw new Error(`${this.key.toString()} Doesn't exist on ${JSON.stringify(value, null, 2)}`);
return <K>value[this.key];
}
@ -143,6 +149,16 @@ export class Cache<K extends string | number | symbol, T> {
return this;
}
/**
* Find the first cached item to match a filter
* @param {Partial<T>} filter Partial item to match
* @param {Boolean} expired Include expired items, defaults to false
* @returns {T | undefined} Cached item or undefined if nothing matched
*/
find(filter: Partial<T>, expired?: boolean): T | undefined {
return <T>Object.values(this.store).find((row: any) => (expired || !row._expired) && includes(row, filter));
}
/**
* Get item from the cache
* @param {K} key Key to lookup