UNPKG

@httpc/kit

Version:

httpc toolbox for building function-based API with minimal code and end-to-end type safety

80 lines (79 loc) 3.28 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; import { singleton } from "tsyringe"; import { alias, KEY, options } from "../di"; import { logger } from "../logging"; import { BaseService } from "../services"; import { LogCacheDecorator } from "./LogCacheDecorator"; import { PrefixCacheDecorator } from "./PrefixCacheDecorator"; let CachingService = class CachingService extends BaseService() { constructor(logger, options) { //@ts-expect-error super(...arguments); this.options = options; this.factories = new Map(); this.caches = new Map(); if (options?.caches) { for (const key in options.caches) { this.register(key, options.caches[key]); } } } getCache(key, options) { let cache = this.caches.get(key); if (!cache) { cache = this._instantiateCache(key); this.caches.set(key, cache); } else { this.logger.verbose("Cache(%s) active", key); } if (!cache) { this._raiseError("not_found", { cache: key }); } if (this.options?.log) { cache = new LogCacheDecorator(key, this.logger, cache); this.logger.verbose("Decorated cache(%s) with LogDecorator", key); } if (options?.prefix) { cache = new PrefixCacheDecorator(options.prefix, cache); this.logger.verbose("Decorated cache(%s) with PrefixDecorator(prefix=%s)", key, options.prefix); } return cache; } removeCache(key) { this.caches.delete(key); this.logger.info("Cache(%s) removed", key); } register(key, factory) { this.factories.set(key, factory); this.logger.info("Registered cache(%s)", key); } _instantiateCache(key) { const factory = this.factories.get(key); if (!factory) { this._raiseError("not_found", { cache: key }); } const instance = factory(this); this.logger.info("Cache(%s) instantiated", key); return instance; } }; CachingService = __decorate([ singleton(), alias(KEY("ICachingService")), __param(0, logger()), __param(1, options(undefined)), __metadata("design:paramtypes", [Object, Object]) ], CachingService); export { CachingService };