session
session copied to clipboard
Not able to store data into session after asynchronous method
// DB connection file
const store = MySQL({
database: 'next-test',
host: 'localhost',
user: 'root',
password: 'root',
port: 8889,
});
bot.use(session({ store, defaultSession: () => ({}) }));
bot.command(commandsList.start.command, async (ctx) => {
const { getUserInfo } = useUserApi(ctx);
const token = ctx.update.message.text.trim().replace('/start ', '').replace('-', '|').trim();
if (token.length > 0 && ctx.update.message.text != '/start' && token.includes('|')) {
try {
// this is working fine
ctx.session.userAuthToken = token;
const user_info: any = await getUserInfo(token);
if (user_info) {
// this is not working
ctx.session.userAuthToken = token;
ctx.session.user_id = user_info.user.user_id;
ctx.session.email = user_info.user.email;
ctx.reply(`${translate('login_success_msg')}`, {
reply_markup: {
remove_keyboard: true,
},
});
} else {
ctx.session.userAuthToken = '';
}
console.log('🚀 ~ bot.command ~ ctx.session:', ctx.session);
} catch (error) {
console.log(error);
ctx.reply(`${translate('something_wrong')}`, {
reply_markup: {
keyboard: replyWithKeyboard,
resize_keyboard: true,
},
});
}
} else {
if (!ctx.session.userAuthToken) {
ctx.reply(`${translate('start_msg')}`, {
reply_markup: {
keyboard: replyWithKeyboard,
resize_keyboard: true,
},
});
}
}
});
The real issue isn't here but somewhere else where you have a missing await. This usually somewhere that you have called next(), but you haven't awaited or returned it.
Also see: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md#how-to-use-session-safely