import _ from "lodash"; import MetricService from "../services/metric.service"; import { DDBConnector } from "./connector/DDBConnector"; export abstract class AbstractModel { idPrefix: string; connector: DDBConnector; metricService: MetricService; constructor(connector: DDBConnector) { this.idPrefix = ""; this.connector = connector; this.metricService = MetricService.getInstance(); } async findById(id: string | number, suffix: string | null = null): Promise { const key = this.buildCbKey(id, suffix); return this.connector.get(key); } async findByMultipleId( ids: (string | number)[], suffix: string | null = null ): Promise> { const keysToIds: Record = {}; const keys: string[] = []; for (const id of ids) { const key = this.buildCbKey(id, suffix); keysToIds[key] = id; keys.push(key); } const items = await this.connector.batchGet(keys); return _.mapKeys(items, (_v, k) => keysToIds[k]); } save(id: string | number, data: any, options = { expiry: 86400 }) { const key = this.buildCbKey(id); return this.connector.save(key, data, options); } async counter(id: string | number, delta: number = 1) { const key = this.buildCbKey(id); return this.connector.counter(key, delta); } private buildCbKey(id: string | number, suffix: string | null = null): string { let key = id + ""; if (key.substring(0, this.idPrefix.length) !== this.idPrefix) { key = this.idPrefix + key; } if (suffix !== null) { key += suffix; } return key; } }