@bitblit/ratchet-aws
Version:
Common tools for use with AWS browser and node
49 lines • 2.11 kB
JavaScript
import { RequireRatchet } from '@bitblit/ratchet-common/lang/require-ratchet';
import { Logger } from '@bitblit/ratchet-common/logger/logger';
export class S3ExpiringCodeProvider {
s3CacheRatchet;
keyName;
constructor(s3CacheRatchet, keyName) {
this.s3CacheRatchet = s3CacheRatchet;
this.keyName = keyName;
RequireRatchet.notNullOrUndefined(s3CacheRatchet, 's3CacheRatchet');
RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(s3CacheRatchet.getDefaultBucket(), 's3CacheRatchet.defaultBucket');
RequireRatchet.notNullUndefinedOrOnlyWhitespaceString(keyName, 'keyName');
}
async fetchFile() {
const rval = (await this.s3CacheRatchet.fetchCacheFileAsObject(this.keyName)) || {
data: [],
lastModifiedEpochMS: Date.now(),
};
return rval;
}
async updateFile(vals) {
const next = {
data: vals || [],
lastModifiedEpochMS: Date.now(),
};
next.data = next.data.filter((d) => d.expiresEpochMS > Date.now());
Logger.info('Updating code file to %s codes', next.data.length);
const rval = await this.s3CacheRatchet.writeObjectToCacheFile(this.keyName, next);
return rval;
}
async checkCode(code, context, deleteOnMatch) {
const val = await this.fetchFile();
const rval = val.data.find((d) => d?.code?.toUpperCase() === code?.toUpperCase() && d?.context?.toUpperCase() === context?.toUpperCase());
if (rval) {
if (deleteOnMatch || rval.expiresEpochMS < Date.now()) {
Logger.info('Stripping used/expired code from the database');
const newData = val.data.filter((d) => d != rval);
await this.updateFile(newData);
}
}
return !!rval && rval.expiresEpochMS > Date.now();
}
async storeCode(code) {
const old = await this.fetchFile();
old.data.push(code);
const wrote = await this.updateFile(old.data);
return !!wrote;
}
}
//# sourceMappingURL=s3-expiring-code-provider.js.map