aboutsummaryrefslogtreecommitdiff
path: root/packages/server/src/cache/index.ts
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2021-08-18 17:29:55 +0200
committerHampusM <hampus@hampusmat.com>2021-08-18 17:29:55 +0200
commitd1a1b7dc947063aef5f8375a6a1e03246b272c84 (patch)
treef5cb9bd6d4b5463d9d022026ac6fea87cb6ebe02 /packages/server/src/cache/index.ts
parent6ed078de30a7bf35deace728857d1d293d59eb15 (diff)
Implemented caching for certain API endpoints, Added documentation & made backend-fixes
Diffstat (limited to 'packages/server/src/cache/index.ts')
-rw-r--r--packages/server/src/cache/index.ts64
1 files changed, 64 insertions, 0 deletions
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<CacheConfig, "enabled">) {
+ 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<T extends new(...args: any[]) => CacheSource>(Source: T, ...args: ConstructorParameters<T>): Promise<unknown> {
+ 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<void> {
+ 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