Created
December 20, 2020 01:14
-
-
Save Jordan-Hall/665b24c4d2a03f39b95cc1da2c97b5fa to your computer and use it in GitHub Desktop.
redis-session.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { connect, Redis } from "https://deno.land/x/redis/mod.ts"; | |
import { SessionStore } from "https://deno.land/x/[email protected]/src/security/session/src/store/store.interface.ts"; | |
type StringKeyObject = { [key: string]: unknown }; | |
export class RedisSession<T = StringKeyObject> implements SessionStore { | |
private redis?: Redis; | |
private allSid: string[] = []; | |
constructor(protected hostname: string, protected port: number) {} | |
async init(): Promise<void> { | |
const redis = await connect({ | |
hostname: "127.0.0.1", | |
port: 6379, | |
}); | |
this.redis = redis; | |
return Promise.resolve(); | |
} | |
async create(sid: string): Promise<void> { | |
await this.redis?.set(sid, JSON.stringify({})); | |
this.allSid.push(sid); | |
return Promise.resolve(); | |
} | |
async delete(sid: string): Promise<void> { | |
await this.redis?.del(sid); | |
return Promise.resolve(); | |
} | |
async get(sid: string): Promise<T | StringKeyObject | undefined> { | |
const itemAsString = await this.redis?.get(sid); | |
if (itemAsString) { | |
return JSON.parse(itemAsString); | |
} | |
} | |
async exist(sid: string): Promise<boolean> { | |
return Boolean(await this.redis?.exists(sid)); | |
} | |
async getValue(sid: string, key:string): Promise<T | undefined> { | |
const item = await this.get(sid) as StringKeyObject; | |
if (item) { | |
return item[key] as T | |
} | |
return; | |
} | |
async setValue(sid: string, key: string, value: unknown): Promise<void> { | |
const obj = await this.get(sid); | |
if (obj) { | |
await this.redis?.set( | |
sid, | |
JSON.stringify({ | |
...obj, | |
[key]: value | |
}) | |
) | |
} | |
return Promise.resolve(); | |
} | |
async clear(): Promise<void> { | |
await Promise.all(this.allSid.map(sid => this.delete(sid))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment