Search code examples
javascriptnode.jsmongodbexpresskoa

What to put in get/set/destroy methods on koa-session DB instance?


I am trying to store the sessions of my Koa app on a mongo DB server.

I do not really understand how works this part of the documentation: https://github.com/koajs/session/blob/master/Readme.md#external-session-stores

It says we have to add three methods (get/set/destroy) to our DB instance. In my case, I have no idea what to put in these functions.

Would someone help me ? At least for get()

Thanks!


Solution

  • As a reference, you can take a look at this session store which is using RethinkDB.

    export function getRethinkSessionStore (dbConn, tableName = 'session') {
      return {
        // Get session object by key.
        get: (key, ageMax, { rolling }) => 
          r.table(tableName).get(key)('session')
            .run(dbConn)
            .catch(err => null),
    
        // Set session object for key, with a maxAge (in ms).
        set: (key, session, maxAge, { rolling, changed }) =>
          r.table(tableName).insert({id: key, maxAge, session}, {conflict: 'replace'})
            .run(dbConn)
            .catch(err => {}),
    
        // Destroy session for key.
        destroy: key => 
          r.table(tableName).delete(key)
            .run(dbConn)
            .catch(err => {})
      }
    }