telegraf / session

Official storage adapters for Telegraf v4.12+ sessions
MIT License
34 stars 6 forks source link

ctx.session is undefined when key in Redis was not found #4

Closed justmavi closed 10 months ago

justmavi commented 10 months ago

Desciption

Instead of creating a new key (as telegraf-session-redis does), @telegraf/session/redis does nothing. When a new user clicks on the Start button, it's clear that his key doesn't currently exist in the storage, and I get an exception when trying to access ctx.session. But when I create a key manually in Redis, everything works fine. But I can't create a key manually for each new user :(

Is this an issue or am I doing something wrong?

Code

import { session } from 'telegraf'
import { Redis } from '@telegraf/session/redis'

const opts = {
    host: process.env.REDIS_HOST ?? 'localhost',
    port: process.env.REDIS_PORT ?? 6379,
    db: process.env.REDIS_DB ?? 0,
}

const bot = new Telegraf(token, opts);
bot.use(session({ store: redisStore(opts) }));

const redisStore = (opts) => {
  let url = 'redis://';

  if (opts.username) {
    url += opts.username;

    if (opts.password) url += `:${opts.password}`;
    url += '@';
  }
  if (opts.host) url += opts.host;
  if (opts.port) url += `:${opts.port}`;
  if (opts.db) url += `/${opts.db}`;

  return Redis({ url });
};

Current behavior

"TypeError: Cannot read properties of undefined (reading 'key')"

Expected behavior

User's session

MKRhere commented 10 months ago

You should tell it what to default to:

bot.use(session({ store: redisStore(opts), defaultSession: () => ({}) }));
justmavi commented 10 months ago

Thank you for your answer. I'll try it a little later. But if the problem is here, then it's better to update the documentation and specify it.

justmavi commented 10 months ago

That works. Thank you )