koajs / generic-session

koa session store with memory, redis or others.
MIT License
414 stars 65 forks source link

Correct implementation for SessionStore #139

Closed lybrus closed 2 years ago

lybrus commented 3 years ago

Hi,

I've just confused. I've just started using TypeScript. How to implement the store. Type definition makes to do it using es2015 syntax.

const getStore = (): SessionStore => {
    function Store(this: EventEmitter) {
        EventEmitter.call(this)

        return Store
    }

    Store.prototype = Object.create(EventEmitter.prototype)
    Store.prototype.constructor = Store

    Store.get = async (sid: string): Promise<unknown> => {
        // get implementation
    }

    Store.set = async (sid: string, sess: Session): Promise<void> => {
        // set implementation
    }

    Store.destroy = async (sid: string): Promise<void> => {
        // destroy implementation
    }

    return Store
}

It would be much better to use classes, something like this.

class Store extends EventEmitter implements SessionStore {
    constructor () {
        super()
    }

    async get (sid: string): Promise<unknown> {
        // get implementation
    }

    async set (sid: string, sess: Session): Promise<void> {
        // set implementation
    }

    async destroy (sid: string): Promise<void> {
        // destroy implementation
    }
}
javiertury commented 2 years ago

I fail to see the problem, your class is fine and it should work if you create an instance.

const store = new Store();

app.use(session({ store }))

Take a look at MemoryStore in this package, it's a class too.

https://github.com/koajs/generic-session/blob/abef2b39358489f459cb993553ef6f10fa7bc9bf/src/memory_store.js#L18-L36