olexnzarov / telegraf-session-mongodb

MongoDB session middleware for Telegraf
25 stars 14 forks source link

Cannot make it working using Mongoose.Connection #15

Closed cod3rshotout closed 2 years ago

cod3rshotout commented 2 years ago

I have this class:

import * as Mongoose from 'mongoose'
import { UserModel } from './users/users.model'
import { ChatModel } from './chats/chats.model'
import { MessageModel } from './messages/messages.model'

const { DB_USER, DB_PASSWORD } = process.env

if (!DB_USER) throw new TypeError('DB_USER missing!')
if (!DB_PASSWORD) throw new TypeError('DB_PASSWORD missing!')

let database: Mongoose.Connection

export const connect = (callback: Function) => {

    const uri = `mongodb+srv://${DB_USER}:${DB_PASSWORD}@cluster0.4ivju.mongodb.net/?retryWrites=true&w=majority`

    if (database) {
        return
    }

    Mongoose.connect(uri)

    database = Mongoose.connection

    database.once('open', async () => {
        console.log('Connected to database')

        callback()
    })

    database.on('error', () => {
        console.log('Error connecting to database')
    })

    return {
        UserModel,
        ChatModel,
        MessageModel
    }
}

export const disconnect = () => {

    if (!database) {
        return
    }

    Mongoose.disconnect()
}

I use the class in the following way:

import { connect } from './database.ts'

import { connect } from './database/database'
import bot from './config/bot'
import { searchCron } from './crons'

connect(() => {

    bot.launch().then(() => console.log('Bot started'))
})

within the bot configuration I have this:

`import { session } from 'telegraf-session-mongoose'`

const bot = new Telegraf<TelegrafContext>(BOT_TOKEN)

// =========== SESSION ===========
bot.use(session({
    sessionName: 'session',
    collectionName: 'sessions'
}))

bot.use(i18n.middleware())

No error appears but when I try to use ctx.i18n.t('example'), instead of getting the message corresponding to "example", the bot prints me "example".

I think there is something I did wrong in the config, how can I fix this?