-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmongodb.ts
71 lines (64 loc) · 2.36 KB
/
mongodb.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { MongoClient, MongoClientOptions } from "mongodb";
import { defaults } from "./defaults";
import { SessionStore } from "./types";
interface NewClientOpts {
/** MongoDB connection URL; required. */
url: string;
/**
* MongoDB MongoClientOptions.
*
* Remember to install the db driver `'mongodb'`.
*
* @see {@link https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connection-options MongoDB | Connection Options}
* */
config?: MongoClientOptions;
/** The name of the database we want to use. If not provided, database name will be taken from connection string. */
database?: string;
/** MongoDB collection name to use for sessions. Defaults to "telegraf-sessions". */
collection?: 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: MongoClient;
/** The name of the database we want to use. If not provided, database name will be taken from connection string. */
database?: string;
/** MongoDB collection name to use for sessions. Defaults to "telegraf-sessions". */
collection?: string;
/** Called on fatal connection or setup errors */
onInitError?: (err: unknown) => void;
}
/** @unstable */
export function Mongo<Session>(opts: NewClientOpts): SessionStore<Session>;
export function Mongo<Session>(opts: ExistingClientOpts): SessionStore<Session>;
export function Mongo<Session>(opts: NewClientOpts | ExistingClientOpts): SessionStore<Session> {
interface SessionDoc {
key: string;
session: Session;
}
let client: MongoClient;
let connection: Promise<MongoClient> | undefined;
if ("client" in opts) client = opts.client;
else {
client = new MongoClient(opts.url, opts.config);
connection = client.connect();
connection.catch(opts.onInitError);
}
const collection = client.db(opts.database).collection<SessionDoc>(opts.collection ?? defaults.table);
return {
async get(key) {
// since we synchronously return store instance
await connection;
return (await collection.findOne({ key }))?.session;
},
async set(key: string, session: Session) {
await connection;
await collection.updateOne({ key }, { $set: { key, session } }, { upsert: true });
},
async delete(key: string) {
await connection;
await collection.deleteOne({ key });
},
};
}