Reputation: 6886
How does one hook up koa-session to a mysql store? It doesn't look like a mysql-store has been developed yet, so I suppose I could develop that. Are there any other solutions other than building out the store?
Upvotes: 1
Views: 1250
Reputation: 6886
from my previous answer, I have published this code onto github and npm. The code shouldn't be ahrd tp extend to other relational DBs:
https://github.com/tb01923/koa-mysql-session
Upvotes: 1
Reputation: 6886
I am trying to build a mysql koa sessions store following the connect mysql-session-store logic / SQL. I am also looking at koa-redis and koa-generic-session/memory_store for approach. Essentially the session store presents an object with get(sid) and set(sid, obj) methods.
Both koa session store objects have these signatures:
Store.prototype.get = function *(sid) {
return session;
};
Store.prototype.set = function *(sid, val, ttl) { };
Store.prototype.destroy = function *(sid) { };
Therefore I coded these up:
MysqlStore.prototype.get = function *(sid) {
let connection = this.getConnection()
let results = yield connection.query(GET_STATEMENT, [sid])
let session = null ;
if(results && results[0] && results[0][0] && results[0][0].data){
session = JSON.parse(results[0][0].data);
}
return session
};
MysqlStore.prototype.set = function *(sid, session, ttl) {
let expires = getExpiresOn(session, ttl).valueOf()
let data = JSON.stringify(session);
let connection = this.getConnection()
let results = yield connection.query(SET_STATEMENT, [sid, expires, data, expires, data])
return results
};
MysqlStore.prototype.destroy = function *(sid) {
let connection = this.getConnection()
let results = yield connection.query(DELETE_STATEMENT, [sid])
};
With the constructor responsible for the mysql connection pool (via co-mysql) and setting up the table in the DB for the session:
var MysqlStore = function (options) {
this.getConnection = function(){
let connection = mysql.createPool(options) ;
return connection ;
}
this.setup = co(function*() {
let connection = this.getConnection()
let result = yield connection.query(CREATE_STATEMENT)
})
this.setup()
};
At some point I will seek some advice to publish this solution on github and NPM. I want to make sure I am honoring the used libraries and licenses first. The project will be here: https://github.com/tb01923/koa-mysql-session
Upvotes: 0