UNPKG

@amirmarmul/waba-common

Version:

![GitHub release](https://img.shields.io/github/v/release/amirmarmul/waba-common?style=flat-square)

104 lines (103 loc) 2.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Repo = void 0; class Repo { store; ttl; constructor(store) { this.store = store; this.ttl = 3600; } async has(key) { return !!await this.get(key); } async missing(key) { return !await this.has(key); } async get(key, _default) { const value = await this.store.get(this.itemKey(key)); return value || await this.value(_default); } async pull(key, _default) { const value = await this.get(key); if (value) { await this.forget(key); } return value || await this.value(_default); } async put(key, value, ttl = this.ttl) { const seconds = this.getSeconds(ttl); if (seconds <= 0) { return await this.forget(key); } const result = await this.store.put(this.itemKey(key), value, seconds); return result; } async add(key, value, ttl = this.ttl) { let seconds = undefined; if (!ttl) { seconds = this.getSeconds(ttl); if (seconds <= 0) { return false; } } if (await this.missing(key)) { return await this.put(key, value, seconds); } return false; } async forever(key, value) { const result = await this.store.forever(this.itemKey(key), value); return result; } async remember(key, callback, ttl = this.ttl) { let value = await this.get(key); if (value) { return value; } value = await this.value(callback); await this.put(key, value, ttl); return value; } async rememberForever(key, callback) { let value = await this.get(key); if (value) { return value; } value = await this.value(callback()); await this.forever(key, value); return value; } async forget(key) { const result = await this.store.forget(this.itemKey(key)); return result; } async flush() { const result = await this.store.flush(); return result; } getDefaultCacheTime() { return this.ttl; } setDefaultCacheTime(ttl) { this.ttl = ttl; return this; } getStore() { return this.store; } setStore(store) { this.store = store; return this; } itemKey(key) { return this.store.getPrefix() + key; } getSeconds(ttl) { return ttl; } async value(value) { return typeof value === 'function' ? await value() : value; } } exports.Repo = Repo;