RealSpeaker / telegraf-session-local

Telegraf local sessions middleware with multiple supported storage types (Memory/FileSync/FileAsync/...) using lowdb
https://git.io/v7iw9
MIT License
93 stars 10 forks source link

read/write values of another session #16

Closed CaiooAndrade closed 6 years ago

CaiooAndrade commented 6 years ago

Hi, I'm learning about this library. Could I be able to access values from other sessions? I'm trying like this,

const session = (new LocalSession({ database: 'example_db.json' })); bot.use(session.middleware()); console.log(session.getSession('170062604:170062604')); //<-- This like gives me the error below TypeError: Cannot read property '_' of undefined

TemaSM commented 6 years ago

Hi @Iniro, Thanks for your question!

Short answer: You are trying to use sessions database synchronously, but it even didn't initialized yet. Simply set storage type to be synchronous, so your code will looks like:

const session = new LocalSession({
  database: 'example_db.json',
  storage: LocalSession.storageFileSync
})
bot.use(session.middleware());
console.log(session.getSession('170062604:170062604'));

Detailed answer: As default telegraf-session-local uses asynchronous storage file adapter for lowdb: https://github.com/RealSpeaker/telegraf-session-local/blob/14c0a9f297e03062f181c138bf87fa1edf23740c/lib/session.js#L1-L6 https://github.com/RealSpeaker/telegraf-session-local/blob/14c0a9f297e03062f181c138bf87fa1edf23740c/lib/session.js#L24-L27 And there's a little bug - we cannot use sessions database before it actually initialized. Meanwhile I'm working on telegraf-session-local, you can simply set storage type to be synchronous, like:

const session = new LocalSession({
  database: 'example_db.json',
  storage: LocalSession.storageFileSync
})

It's not so easy to keep code backward compatible, but I will try to introduce in v0.0.6 something new on how to deal with asynchronous adapters.

CaiooAndrade commented 6 years ago

Thank you, your response was extremely helpful.

TemaSM commented 6 years ago

@Iniro now you can access database (and sessions in it) in two ways:

  1. Synchronous storage (LocalSession.storageFileSync - default storage adapter since v0.0.6):

    const session = new LocalSession()
    bot.use(session.middleware())
    console.log(session.getSession('170062604:170062604'))
  2. Asynchronous storage (LocalSession.storageFileAsync):

    const session = new LocalSession({
    storage: LocalSession.storageFileAsync,
    })
    bot.use(session.middleware())
    session.DB.then((db) => {
    console.log(db.get('sessions').getById('170062604:170062604').value())
    })