webstore/ts/webstore.classes.typedrequestcache.ts

48 lines
1.3 KiB
TypeScript

import { WebStore } from './webstore.classes.webstore.js';
import * as plugins from './webstore.plugins.js';
/**
* a cache that can be used to store and retrieve typedrequests
*/
export class TypedrequestCache {
private webstore: WebStore;
constructor(domainArg = 'default') {
this.webstore = new WebStore<plugins.typedrequestInterfaces.ITypedRequest>({
dbName: 'trStore',
storeName: `trStore-${domainArg}`,
});
}
private buildKey(requestArg: plugins.typedrequestInterfaces.ITypedRequest) {
return plugins.smartjson.stringify({
method: requestArg.method,
request: requestArg.request,
});
}
/**
* stores by request
* @param typedrequestarg
*/
public async setByRequest(
typedrequestArg: plugins.typedrequestInterfaces.ITypedRequest
): Promise<void> {
if (!typedrequestArg.response) {
throw new Error('You cannot store requests without a response present');
}
await this.webstore.set(this.buildKey(typedrequestArg), typedrequestArg);
}
/**
* get by full tyoedrequest by partial typedrequest
* @param typedrequestarg
*/
public async getByRequest(
typedrequestArg: plugins.typedrequestInterfaces.ITypedRequest
): Promise<plugins.typedrequestInterfaces.ITypedRequest> {
const result = await this.webstore.get(this.buildKey(typedrequestArg));
return result;
}
}