From 8d385c28280168dbd9f5ca528639ffa60312731a Mon Sep 17 00:00:00 2001 From: H <81833521+movwf@users.noreply.github.com> Date: Thu, 11 May 2023 22:25:42 +0300 Subject: [PATCH] Add TTL interception for external conditional TTL handling (#393) --- index.ts | 8 ++++++-- readme.md | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/index.ts b/index.ts index 88af6a0..8079b17 100644 --- a/index.ts +++ b/index.ts @@ -21,7 +21,7 @@ interface RedisStoreOptions { prefix?: string scanCount?: number serializer?: Serializer - ttl?: number + ttl?: number | {(sess: SessionData): number} disableTTL?: boolean disableTouch?: boolean } @@ -31,7 +31,7 @@ class RedisStore extends Store { prefix: string scanCount: number serializer: Serializer - ttl: number + ttl: number | {(sess: SessionData): number} disableTTL: boolean disableTouch: boolean @@ -181,6 +181,10 @@ class RedisStore extends Store { } private _getTTL(sess: SessionData) { + if (typeof this.ttl === "function") { + return this.ttl(sess) + } + let ttl if (sess && sess.cookie && sess.cookie.expires) { let ms = Number(new Date(sess.cookie.expires)) - Date.now() diff --git a/readme.md b/readme.md index 7c26f1b..9c18802 100644 --- a/readme.md +++ b/readme.md @@ -89,6 +89,15 @@ If the session cookie has a `expires` date, `connect-redis` will use it as the T Otherwise, it will expire the session using the `ttl` option (default: `86400` seconds or one day). +```ts +interface RedisStoreOptions { + ... + ttl?: number | {(sess: SessionData): number} +} +``` + +`ttl` also has external callback support. You can use it for dynamic TTL generation. It has access to `session` data. + **Note**: The TTL is reset every time a user interacts with the server. You can disable this behavior in _some_ instances by using `disableTouch`. **Note**: `express-session` does not update `expires` until the end of the request life cycle. _Calling `session.save()` manually beforehand will have the previous value_.