This commit is contained in:
2023-08-14 14:36:45 -04:00
commit b5966f98b2
94 changed files with 21124 additions and 0 deletions

View File

@ -0,0 +1,98 @@
import {includes} from '@transmute/common';
import {distinctUntilChanged, map, Observable, share} from 'rxjs';
import {ReactiveCache} from './reactiveCache';
import {CrudApiEndpoint} from './endpoint';
export abstract class CrudApiClient<K, T> {
public abstract api: CrudApiEndpoint<K, T>;
protected readonly cache = new ReactiveCache<K, T>();
protected readonly groups = new ReactiveCache<Partial<T>, K[]>();
protected readonly pending = new ReactiveCache<K | Partial<T>, Promise<T | T[]>>();
clear() {
this.cache.clear();
this.groups.clear();
this.pending.clear();
}
list(filter?: Partial<T>, reload?: boolean): Promise<T[]> {
const ck = filter ?? {};
if(!reload) {
const cache = this.groups.get(ck);
if(cache) return Promise.resolve(cache.map(k => <T>this.cache.get(k)));
const pending = this.pending.get(ck);
if(pending) return <Promise<T[]>>pending;
}
return <Promise<T[]>>this.pending.set(ck, this.api.list(filter).then(rows => {
this.groups.set(ck, rows.map(r => {
const pk = (<any>r)[this.api.pk.toString()];
this.cache.set(pk, r);
return pk;
}));
return rows;
}).finally(() => this.pending.delete(ck)));
}
create(value: T): Promise<T> {
return this.api.create(value).then(row => {
const pk = (<any>row)[this.api.pk];
this.cache.set(pk, row);
this.groups.entries.forEach(([key, cached]) => {
if(includes(row, key, true))
this.groups.set(key, [...cached, pk]);
});
return row;
});
}
read(filter: K | Partial<T>, reload?: boolean): Promise<T> {
const pk = typeof filter == 'object' ? (<any>filter)[this.api.pk] : filter;
if(!reload) {
const cache = this.cache.get(pk);
if(cache) return Promise.resolve(cache);
const pending = this.pending.get(pk);
if(pending) return <Promise<T>>pending;
}
return <Promise<T>>this.pending.set(filter, this.api.read(filter).then(row => {
this.cache.set(pk, row);
this.groups.entries.forEach(([key, cached]) => {
if(includes(row, key, true))
this.groups.set(key, [...cached, pk]);
});
return row;
}).finally(() => this.pending.delete(pk)));
}
update(value: Partial<T>): Promise<T> {
return this.api.update(value).then(row => {
const pk = (<any>row)[this.api.pk];
this.cache.set(pk, row);
this.groups.entries.forEach(([key, cached]) => {
if(includes(row, key, true))
this.groups.set(key, [...cached, pk]);
});
return row;
});
}
delete(filter: K | Partial<T>): Promise<void> {
const pk = typeof filter == 'object' ? (<any>filter)[this.api.pk] : filter;
return this.api.delete(filter).then(() => {
this.cache.delete(pk);
this.groups.entries.forEach(([key, cached]) => {
this.groups.set(key, cached.filter(k => k != pk));
});
});
}
listen(filter?: K | Partial<T>): Observable<T[]> {
const key: Partial<T> = <any>(filter == null ? {} : typeof filter == 'object' ? filter : {[this.api.pk]: filter});
this.list(key);
return this.cache.events.pipe(
map(cached => cached.filter(c => includes(c, key))),
distinctUntilChanged(),
share()
);
}
}

View File

@ -0,0 +1,52 @@
import {HttpClient} from '@angular/common/http';
export abstract class CrudApiEndpoint<K, T> {
protected abstract http: HttpClient;
getUrl!: (value?: K | Partial<T>) => string;
protected constructor(private readonly url: string, public readonly pk: keyof T) {
const parts = url.split('/');
if(url.indexOf('://') != -1) {
const protocol = parts.splice(0, 2)[0];
parts[0] = `${protocol}//${parts[0]}`;
}
this.getUrl = (value?: K | Partial<T>) => {
if(value == null) value = {};
if(typeof value != 'object') value = <Partial<T>>{[this.pk]: value};
let last: number;
let newUrl: string = parts.map((p, i) => {
if(p[0] != ':') return p;
last = i;
const optional = p.slice(-1) == '?';
const key = p.slice(1, optional ? -1 : undefined);
const val = (<any>value)?.[key];
if(val == undefined && !optional)
throw new Error(`'The request to "${url}" is missing the following key: ${key}\n\n${JSON.stringify(value)}`);
return val;
}).filter((p, i) => !!p || i > last).join('/');
return newUrl;
};
}
list(filter?: Partial<T>, paginate?: { offset?: number; limit?: number }): Promise<T[]> {
return <any>this.http.get<T[]>(this.getUrl(filter), {params: paginate}).toPromise();
}
create(value: T): Promise<T> {
return <any>this.http.post<T>(this.getUrl(value), value).toPromise();
}
read(filter: K | Partial<T>): Promise<T> {
return <any>this.http.get<T>(this.getUrl(filter)).toPromise();
}
update(value: Partial<T>): Promise<T> {
return <any>this.http.patch<T>(this.getUrl(value), value).toPromise();
}
delete(filter: K | Partial<T>): Promise<void> {
return this.http.delete<void>(this.getUrl(filter)).toPromise();
}
}

View File

@ -0,0 +1,94 @@
import {Subject} from 'rxjs';
/**
* A mapped cached which accepts anything as a key. This is accomplished by serializing the values using
* `JSON.stringify`. Objects go through the extra step of having their properties
* sorted to ensure their order.
* @template K - How the cache should be indexed
* @template T - The type that will be cached
*/
export class ReactiveCache<K, T> {
/** This is where everything is actually stored */
private store = new Map<string, T>();
events = new Subject<T[]>();
/** Tuple array of keys & values */
get entries(): [K, T][] { return [...this.store.entries()].map(([key, val]) => [!key ? key : JSON.parse(key), val]) }
/** Cache keys in use */
get keys(): K[] { return [...this.store.keys()].map(k => !k ? k : JSON.parse(k)); }
/** Number of cached items */
get size(): number { return this.store.size; }
/** Returns all the stored rows */
get values(): T[] { return [...this.store.values()]; }
/**
* Serializes anything with order guaranteed (Array positions wont change & object properties are sorted)
* @param value - Anything that needs to be serialized
* @returns {string} - The serialized version of the data
* @private
*/
private static serialize(value: any) {
const _serialize: (value: any) => string = (value: any) => {
if(Array.isArray(value)) return value.map(v => _serialize(v));
if(value != null && typeof value == 'object') return Object.keys(value).sort()
.reduce((acc, key) => ({...acc, [key]: _serialize(value[key])}), {});
return value;
};
return JSON.stringify(_serialize(value));
}
/** Clear everything from the cache */
clear() {
this.store.clear();
this.events.next(this.values);
}
/**
* Delete a cached value
* @param {K} key - Cache key
*/
delete(key: K) {
this.store.delete(ReactiveCache.serialize(key));
this.events.next(this.values);
}
/**
* Find a value stored in the cache
* @param {K} key - Cache key
* @returns {T | undefined} - The cached value, or undefined if nothing is cached under the provided key
*/
get(key: K): T | undefined { return this.store.get(ReactiveCache.serialize(key)); }
/**
* Check if the cache key has an attached value
* @param {K} key - Cache key
* @returns {boolean} - True if cached
*/
has(key: K): boolean { return this.store.has(ReactiveCache.serialize(key)); }
/**
* Store a value in the cache with a cache key
* @param {K} key - Index to store the value under
* @param {T} value - What you will be storing
*/
set(key: K, value: T) {
this.store.set(ReactiveCache.serialize(key), value);
this.events.next(this.values);
return value;
}
}
// export class ApiCache<K, T> {
// cache = new Map<K, T>();
// pending = new Map<K, Promise<T>>();
//
// get(key: K, fetchFn: (key: K) => Promise<T>) {
// if(this.cache[key]) return Promise.reject(this.cache[key]);
// if(this.pending[key]) return this.pending[key];
// return fetchFn(key).then(res => {
// this.cache[key] = res;
// return res;
// }).finally(() => this.pending[key] = undefined);
// }
// }