redis-session-cache-plugin.ts 2.4 KB

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