MCPcopy Create free account
hub / github.com/adonisjs/session / DatabaseStore

Class DatabaseStore

src/stores/database.ts:28–272  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

26 * })
27 */
28export class DatabaseStore implements SessionStoreWithTaggingContract {
29 #client: QueryClientContract
30 #tableName: string
31 #ttlSeconds: number
32 #gcProbability: number
33
34 /**
35 * Creates a new database store instance
36 *
37 * @param client - Lucid query client instance
38 * @param age - Session age in seconds or time expression (e.g. '2 hours')
39 * @param options - Configuration options
40 * @param options.tableName - Database table name (defaults to "sessions")
41 * @param options.gcProbability - Garbage collection probability in percent (defaults to 2)
42 */
43 constructor(
44 client: QueryClientContract,
45 age: string | number,
46 options?: {
47 /**
48 * Defaults to "sessions"
49 */
50 tableName?: string
51
52 /**
53 * The probability (in percent) that garbage collection will be
54 * triggered on any given request. For example, 2 means 2% chance.
55 *
56 * Set to 0 to disable garbage collection.
57 *
58 * Defaults to 2 (2% chance)
59 */
60 gcProbability?: number
61 }
62 ) {
63 this.#client = client
64 this.#tableName = options?.tableName ?? 'sessions'
65 this.#ttlSeconds = string.seconds.parse(age)
66 this.#gcProbability = options?.gcProbability ?? 2
67 debug('initiating database store')
68 }
69
70 /**
71 * Runs garbage collection to delete expired sessions from the database.
72 * Executes probabilistically based on gcProbability setting after writing session data.
73 * Helps maintain database performance by removing stale session records.
74 */
75 async #collectGarbage(): Promise<void> {
76 if (this.#gcProbability <= 0) {
77 return
78 }
79
80 const random = Math.random() * 100
81 if (random < this.#gcProbability) {
82 debug('database store: running garbage collection')
83 const expiredBefore = new Date(Date.now())
84 await this.#client.from(this.#tableName).where('expires_at', '<=', expiredBefore).delete()
85 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected