redis-session-cache-plugin.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { CachedSession, Logger, SessionCacheStrategy, VendurePlugin } from '@vendure/core';
  2. import IORedis from 'ioredis';
  3. const loggerCtx = 'RedisSessionCacheStrategy';
  4. const DEFAULT_NAMESPACE = 'vendure-session-cache';
  5. export class RedisSessionCacheStrategy implements SessionCacheStrategy {
  6. private client: IORedis.Redis;
  7. constructor(private options: RedisSessionCachePluginOptions) {}
  8. init() {
  9. this.client = new IORedis(this.options.redisOptions);
  10. this.client.on('error', err => Logger.error(err.message, loggerCtx, err.stack));
  11. }
  12. async get(sessionToken: string): Promise<CachedSession | undefined> {
  13. const retrieved = await this.client.get(this.namespace(sessionToken));
  14. if (retrieved) {
  15. try {
  16. return JSON.parse(retrieved);
  17. } catch (e) {
  18. Logger.error(`Could not parse cached session data: ${e.message}`, loggerCtx);
  19. }
  20. }
  21. }
  22. async set(session: CachedSession) {
  23. await this.client.set(this.namespace(session.token), JSON.stringify(session));
  24. }
  25. async delete(sessionToken: string) {
  26. await this.client.del(this.namespace(sessionToken));
  27. }
  28. clear() {
  29. // not implemented
  30. }
  31. private namespace(key: string) {
  32. return `${this.options.namespace ?? DEFAULT_NAMESPACE}:${key}`;
  33. }
  34. }
  35. export interface RedisSessionCachePluginOptions {
  36. namespace?: string;
  37. redisOptions?: IORedis.RedisOptions;
  38. }
  39. @VendurePlugin({
  40. configuration: config => {
  41. config.authOptions.sessionCacheStrategy = new RedisSessionCacheStrategy(
  42. RedisSessionCachePlugin.options,
  43. );
  44. return config;
  45. },
  46. })
  47. export class RedisSessionCachePlugin {
  48. static options: RedisSessionCachePluginOptions;
  49. static init(options: RedisSessionCachePluginOptions) {
  50. this.options = options;
  51. return this;
  52. }
  53. }