Skip to content

Commit

Permalink
refactor(core): Unify session cache with new CacheStrategy
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
michaelbromley committed Oct 30, 2024
1 parent 75feeea commit 249d3ec
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 6 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/config/default-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Original file line number Diff line number Diff line change
@@ -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 changes: 3 additions & 0 deletions packages/core/src/config/system/in-memory-cache-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
7 changes: 3 additions & 4 deletions packages/core/src/config/vendure-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down

0 comments on commit 249d3ec

Please sign in to comment.