From d1a1b7dc947063aef5f8375a6a1e03246b272c84 Mon Sep 17 00:00:00 2001 From: HampusM Date: Wed, 18 Aug 2021 17:29:55 +0200 Subject: Implemented caching for certain API endpoints, Added documentation & made backend-fixes --- packages/server/src/cache/index.ts | 64 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 packages/server/src/cache/index.ts (limited to 'packages/server/src/cache/index.ts') diff --git a/packages/server/src/cache/index.ts b/packages/server/src/cache/index.ts new file mode 100644 index 0000000..9bb4abd --- /dev/null +++ b/packages/server/src/cache/index.ts @@ -0,0 +1,64 @@ +/** + * Utilities for managing server-side cache + * + * @module cache + */ + +import { caching, Cache } from "cache-manager"; +import { cacheAllSources, CacheSource } from "./sources"; +import { CacheConfig } from "../types"; + +export *as sources from "./sources"; + +export class ServerCache { + private _cache: Cache; + + public ready = false; + + /** + * @param [config] - Cache configuration from the settings + */ + constructor(config?: Omit) { + this._cache = caching({ + store: "memory", + max: config?.max || 5000000, + ttl: config?.ttl || 120, + refreshThreshold: config?.refreshThreshold || 80 + }); + } + + /** + * Returns the cache value specified in the source & caches it if need be + * + * @template T - The constructor of a cache source + * @param Source - Information about where to get the value from + * @param args - Source arguments + * @returns A value from the cache + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + public async receive CacheSource>(Source: T, ...args: ConstructorParameters): Promise { + const source = new Source(...args); + + const result = await this._cache.wrap(source.key(), () => source.func()) as T; + + return source.post + ? source.post(result) as T + : result; + } + + /** + * Initialize the cache. + * This will cache all of the available sources. + * + * @param git_dir - A git directory + */ + public async init(git_dir: string): Promise { + if(this.ready === true) { + throw(new Error("Cache has already been initialized!")); + } + + await cacheAllSources(this, git_dir); + + this.ready = true; + } +} \ No newline at end of file -- cgit v1.2.3-18-g5258