diff --git a/packages/redis/examples/deno.ts b/packages/redis/examples/deno.ts index f1841da0..60cc35ff 100644 --- a/packages/redis/examples/deno.ts +++ b/packages/redis/examples/deno.ts @@ -14,7 +14,7 @@ const redisInstance = await connect({ }); //create storage -const storage = new RedisAdapter({ instance: redisInstance, ttl: 10 }); +const storage = new RedisAdapter({ instance: redisInstance, ttl: 10, autoParseDates: true }); // Create bot and register session middleware const bot = new Bot(''); diff --git a/packages/redis/examples/node.ts b/packages/redis/examples/node.ts index e90393d7..5b446404 100644 --- a/packages/redis/examples/node.ts +++ b/packages/redis/examples/node.ts @@ -10,7 +10,7 @@ type MyContext = Context & SessionFlavor; const redisInstance = new IORedis('redis://localhost:6379/0'); //create storage -const storage = new RedisAdapter({ instance: redisInstance, ttl: 10 }); +const storage = new RedisAdapter({ instance: redisInstance, ttl: 10, autoParseDates: true }); // Create bot and register session middleware const bot = new Bot(''); diff --git a/packages/redis/src/mod.ts b/packages/redis/src/mod.ts index ffd9a150..5774477c 100644 --- a/packages/redis/src/mod.ts +++ b/packages/redis/src/mod.ts @@ -3,14 +3,16 @@ import { Client, StorageAdapter } from './deps.deno.ts'; export class RedisAdapter implements StorageAdapter { private redis: Client; private readonly ttl?: number; + private readonly autoParseDates: boolean /** * @constructor * @param {opts} Constructor options * @param {opts.ttl} ttl - Session time to life in SECONDS. * @param {opts.instance} instance - Instance of redis. + * @param {opts.autoParseDates} autoParseDates - set to true to convert string in the json date format to date object */ - constructor({ instance, ttl }: { instance?: Client; ttl?: number }) { + constructor({ instance, ttl, autoParseDates }: { instance?: Client; ttl?: number, autoParseDates?: boolean }) { if (instance) { this.redis = instance; } else { @@ -18,6 +20,7 @@ export class RedisAdapter implements StorageAdapter { } this.ttl = ttl; + this.autoParseDates = autoParseDates || false; } async read(key: string) { @@ -25,6 +28,9 @@ export class RedisAdapter implements StorageAdapter { if (session === null || session === undefined) { return undefined; } + if (this.autoParseDates) { + return JSON.parse(session, dateParser) as unknown as T; + } return JSON.parse(session) as unknown as T; } @@ -39,3 +45,17 @@ export class RedisAdapter implements StorageAdapter { await this.redis.del(key); } } + +const ISO_8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?$/; +const dateParser = (key: string, value: any) => { + + if (typeof value === 'string' && ISO_8601.test(value)) { + var newValue; + if (!value.endsWith("Z")) { + newValue = `${value}Z`; + } + else newValue = value + return new Date(newValue); + } + return value; +} \ No newline at end of file