forked from telegraf/session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.ts
55 lines (48 loc) · 1.75 KB
/
redis.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { createClient } from "redis";
import type { RedisClientOptions } from "redis";
import { SessionStore } from "./types";
type Client = ReturnType<typeof createClient>;
interface NewClientOpts {
/**
* `redis[s]://[[username][:password]@][host][:port][/db-number]`
*
* See [`redis`](https://www.iana.org/assignments/uri-schemes/prov/redis) and [`rediss`](https://www.iana.org/assignments/uri-schemes/prov/rediss) IANA registration for more details
*/
url?: string;
config: Omit<RedisClientOptions, "url">;
/** Prefix to use for session keys. Defaults to "telegraf:". */
prefix?: string;
/** Called on fatal connection or setup errors */
onInitError?: (err: unknown) => void;
}
interface ExistingClientOpts {
/** If passed, we'll reuse this client instead of creating our own. */
client: Client;
/** Prefix to use for session keys. Defaults to "telegraf:". */
prefix?: string;
}
/** @unstable */
export function Redis<Session>(opts: NewClientOpts): SessionStore<Session>;
export function Redis<Session>(opts: ExistingClientOpts): SessionStore<Session>;
export function Redis<Session>(opts: NewClientOpts | ExistingClientOpts): SessionStore<Session> {
let client: Client;
if ("client" in opts) client = opts.client;
else client = createClient({ ...opts.config, url: opts.url });
const connection = client.connect();
const prefix = opts.prefix || "telegraf:";
return {
async get(key) {
await connection;
const value = await client.get(prefix + key);
return value ? JSON.parse(value) : undefined;
},
async set(key: string, session: Session) {
await connection;
return await client.set(prefix + key, JSON.stringify(session));
},
async delete(key: string) {
await connection;
return await client.del(prefix + key);
},
};
}