telegraf-session-mongoose
Version:
MongoDB session middleware for Telegraf
39 lines (30 loc) • 1.37 kB
text/typescript
import { Schema, model } from 'mongoose';
import { Context, MiddlewareFn } from 'telegraf';
import { getSessionKey, SessionKeyFunction } from './keys';
export type SessionOptions = {
sessionName: string;
collectionName: string;
sessionKeyFn: SessionKeyFunction;
};
export const session = <C extends Context = Context>(sessionOptions?: Partial<SessionOptions>): MiddlewareFn<C> => {
const options: SessionOptions = {
sessionName: 'session',
collectionName: 'sessions',
sessionKeyFn: getSessionKey,
...sessionOptions
};
const sessionSchema = new Schema({ key: String, data: Object }, { collection: options.collectionName });
const collection = model('Session', sessionSchema);
const saveSession = (key: string, data: any) => collection.updateOne({ key }, { $set: { data } }, { upsert: true });
const getSession = async (key: string) => (await collection.findOne({ key }))?.data ?? {};
const { sessionKeyFn: getKey, sessionName } = options;
return async (ctx: Context, next) => {
const key = getKey(ctx);
const data = key == null ? undefined : await getSession(key);
ctx[sessionName] = data;
await next();
if (ctx[sessionName] != null) {
await saveSession(key, ctx[sessionName]);
}
};
}