Jelajahi Sumber

refactor(core): Unify session cache with new CacheStrategy

Relates to #3043. This commit introduces a new DefaultSessionCacheStrategy, which
delegates to the underlying CacheStrategy. This means that now you only need to
think about the CacheStrategy, and the session cache will use whatever mechanism
is defined there.
Michael Bromley 1 tahun lalu
induk
melakukan
249d3ec390

+ 2 - 2
packages/core/src/config/default-config.ts

@@ -45,7 +45,7 @@ import { UseGuestStrategy } from './order/use-guest-strategy';
 import { defaultPaymentProcess } from './payment/default-payment-process';
 import { defaultPromotionActions, defaultPromotionConditions } from './promotion';
 import { defaultRefundProcess } from './refund/default-refund-process';
-import { InMemorySessionCacheStrategy } from './session-cache/in-memory-session-cache-strategy';
+import { DefaultSessionCacheStrategy } from './session-cache/default-session-cache-strategy';
 import { defaultShippingCalculator } from './shipping-method/default-shipping-calculator';
 import { defaultShippingEligibilityChecker } from './shipping-method/default-shipping-eligibility-checker';
 import { DefaultShippingLineAssignmentStrategy } from './shipping-method/default-shipping-line-assignment-strategy';
@@ -97,7 +97,7 @@ export const defaultConfig: RuntimeVendureConfig = {
         },
         authTokenHeaderKey: DEFAULT_AUTH_TOKEN_HEADER_KEY,
         sessionDuration: '1y',
-        sessionCacheStrategy: new InMemorySessionCacheStrategy(),
+        sessionCacheStrategy: new DefaultSessionCacheStrategy(),
         sessionCacheTTL: 300,
         requireVerification: true,
         verificationTokenDuration: '7d',

+ 1 - 0
packages/core/src/config/index.ts

@@ -73,6 +73,7 @@ export * from './payment/payment-method-eligibility-checker';
 export * from './payment/payment-method-handler';
 export * from './payment/payment-process';
 export * from './promotion';
+export * from './session-cache/default-session-cache-strategy';
 export * from './session-cache/in-memory-session-cache-strategy';
 export * from './session-cache/noop-session-cache-strategy';
 export * from './session-cache/session-cache-strategy';

+ 75 - 0
packages/core/src/config/session-cache/default-session-cache-strategy.ts

@@ -0,0 +1,75 @@
+import { JsonCompatible } from '@vendure/common/lib/shared-types';
+
+import { CacheService } from '../../cache/index';
+import { Injector } from '../../common/injector';
+
+import { CachedSession, SessionCacheStrategy } from './session-cache-strategy';
+
+/**
+ * @description
+ * The default {@link SessionCacheStrategy} delegates to the configured
+ * {@link CacheStrategy} to store the session data. This should be suitable
+ * for most use-cases, assuming you select a suitable {@link CacheStrategy}
+ *
+ * @since 3.1.0
+ * @docsCategory auth
+ */
+export class DefaultSessionCacheStrategy implements SessionCacheStrategy {
+    protected cacheService: CacheService;
+    private readonly tags = ['DefaultSessionCacheStrategy'];
+
+    constructor(
+        private options?: {
+            ttl?: number;
+            cachePrefix?: string;
+        },
+    ) {}
+
+    init(injector: Injector) {
+        this.cacheService = injector.get(CacheService);
+    }
+
+    set(session: CachedSession): Promise<void> {
+        return this.cacheService.set(this.getCacheKey(session.token), this.serializeDates(session), {
+            tags: this.tags,
+            ttl: this.options?.ttl ?? 24 * 60 * 60 * 1000,
+        });
+    }
+
+    async get(sessionToken: string): Promise<CachedSession | undefined> {
+        const cacheKey = this.getCacheKey(sessionToken);
+        const item = await this.cacheService.get<JsonCompatible<CachedSession>>(cacheKey);
+        return item ? this.deserializeDates(item) : undefined;
+    }
+
+    delete(sessionToken: string): void | Promise<void> {
+        return this.cacheService.delete(this.getCacheKey(sessionToken));
+    }
+
+    clear(): Promise<void> {
+        return this.cacheService.invalidateTags(this.tags);
+    }
+
+    /**
+     * @description
+     * The `CachedSession` interface includes a `Date` object, which we need to
+     * manually serialize/deserialize to/from JSON.
+     */
+    private serializeDates(session: CachedSession) {
+        return {
+            ...session,
+            expires: session.expires.toISOString(),
+        } as JsonCompatible<CachedSession>;
+    }
+
+    private deserializeDates(session: JsonCompatible<CachedSession>): CachedSession {
+        return {
+            ...session,
+            expires: new Date(session.expires),
+        };
+    }
+
+    private getCacheKey(sessionToken: string) {
+        return `${this.options?.cachePrefix ?? 'vendure-session-cache'}:${sessionToken}`;
+    }
+}

+ 3 - 0
packages/core/src/config/system/in-memory-cache-strategy.ts

@@ -13,6 +13,9 @@ export interface CacheItem<T> {
  * A {@link CacheStrategy} that stores the cache in memory using a simple
  * JavaScript Map.
  *
+ * This is the default strategy that will be used if no other strategy is
+ * configured.
+ *
  * **Caution** do not use this in a multi-instance deployment because
  * cache invalidation will not propagate to other instances.
  *

+ 3 - 4
packages/core/src/config/vendure-config.ts

@@ -382,11 +382,10 @@ export interface AuthOptions {
     sessionDuration?: string | number;
     /**
      * @description
-     * This strategy defines how sessions will be cached. By default, sessions are cached using a simple
-     * in-memory caching strategy which is suitable for development and low-traffic, single-instance
-     * deployments.
+     * This strategy defines how sessions will be cached. By default, since v3.1.0, sessions are cached using
+     * the underlying cache strategy defined in the {@link SystemOptions.cacheStrategy}.
      *
-     * @default InMemorySessionCacheStrategy
+     * @default DefaultSessionCacheStrategy
      */
     sessionCacheStrategy?: SessionCacheStrategy;
     /**