Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/api/src/shared-store.ts
T

49 lines
1.7 KiB
TypeScript

import { createSharedStore, type SharedStore } from "@hivegrid/shared-store";
/**
* Singleton SharedStore for the API process. All in-process Map-backed
* stores migrated as part of task #38 receive their `SharedStore` from
* this module so the underlying Redis connection (or memory fallback)
* is reused across the API lifetime.
*/
let cachedStore: SharedStore | null = null;
let crossAppCacheStore: SharedStore | null = null;
let factory: () => SharedStore = () => createSharedStore({ namespace: "api", redisUrl: process.env.REDIS_URL });
export function getSharedStore(): SharedStore {
if (cachedStore === null) {
cachedStore = factory();
}
return cachedStore;
}
/**
* Shared namespace for cache invalidations exchanged with other apps. It
* reuses this process's adapter/connection while making the wire channel
* independent from the app-local `api` namespace.
*/
export function getCrossAppCacheStore(): SharedStore {
if (crossAppCacheStore === null) {
crossAppCacheStore = createSharedStore({ namespace: "cross-app-cache", adapter: getSharedStore().adapter });
}
return crossAppCacheStore;
}
/**
* Test seam: override the factory and clear the cached instance. Tests
* call this to inject a SharedStore that uses an in-memory adapter or a
* specific Redis test container.
*/
export function __setSharedStoreFactoryForTests(next: () => SharedStore): void {
factory = next;
cachedStore = null;
crossAppCacheStore = null;
}
/** Test seam: reset to the default factory and drop the cached instance. */
export function __resetSharedStoreForTests(): void {
factory = () => createSharedStore({ namespace: "api", redisUrl: process.env.REDIS_URL });
cachedStore = null;
crossAppCacheStore = null;
}