@widergy/web-utils
Version:
Utility GO! Web utils
60 lines (59 loc) • 2.48 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dayjs_1 = __importDefault(require("dayjs"));
class TransactionContextManager {
constructor() {
this.STORAGE_KEY = 'TRANSACTION_CONTEXT';
this.EXPIRED = 'TRANSACTION_CONTEXT_EXPIRED';
this.NO_CONTEXT = 'NO_CONTEXT';
this.initialize = (saveFunc, deleteFunc, getFunc, expirationMinutes) => {
this.saveFunc = saveFunc;
this.deleteFunc = deleteFunc;
this.getFunc = getFunc;
this.expirationMinutes = expirationMinutes;
};
this.save = async (value) => this.saveFunc(this.STORAGE_KEY, value);
this.get = async () => this.getFunc(this.STORAGE_KEY);
this.delete = async () => this.deleteFunc(this.STORAGE_KEY);
this.isExpired = (date) => {
const diff = (0, dayjs_1.default)().diff((0, dayjs_1.default)(date), 'minute');
return diff > this.expirationMinutes;
};
this.saveTransactionContext = async (transactionName, transactionData) => {
const transactionDate = new Date().toISOString();
const context = {
transactionDate,
transactionName,
transactionData,
};
const stringContext = JSON.stringify(context);
try {
await this.save(stringContext);
return { ok: true, message: `Saved context ${transactionDate}` };
}
catch (error) {
return { ok: false, message: `Couldn't save context ${transactionDate}`, error };
}
};
this.getTransactionContext = async () => {
try {
const stringData = await this.get();
if (!stringData)
return { ok: false, error: this.NO_CONTEXT };
const contextData = JSON.parse(stringData);
await this.delete();
if (this.isExpired(contextData.transactionDate)) {
return { ok: false, error: this.EXPIRED };
}
return { ok: true, contextData };
}
catch (error) {
return { ok: false, error };
}
};
}
}
exports.default = new TransactionContextManager();