This middleware is broken
I just spent an hour debugging this, so consider this an excuse for such header.
The pattern when you read this.flash from one object (data) and write this.flash to another object (this.sesion[key]) is a programmer's nightmare.
You write to an object, read from it, and the result is different from what you've written! That should never happen.
In my case, I was assigning values to this.flash.message = .... Guess where did it go?
It went to defaultValue! All future sessions had this flash enabled by default, on every site page. Oh my.
Please make things simple and clear.
At this moment, I'm using my custom middleware for flash:
app.use(function *flash(next) {
this.flash = this.session.flash || {};
this.session.flash = {};
Object.defineProperty(this, 'newFlash', {
get: function() {
return this.session.flash;
},
set: function(val) {
this.session.flash = val;
}
});
yield *next;
if (this.session && Object.keys(this.session.flash).length == 0) {
// don't write empty flash
delete this.session.flash;
}
if (this.status == 302 && this.session && !this.session.flash) {
// pass on the flash over a redirect
this.session.flash = this.flash;
}
});
Here, you get this.flash as an incoming flash and this.newFlash as an outgoing flash.
By default both objects are {} (that's convenient), but no garbage the in session.
B/R Ilya Kantor
A constructive pull request would be appreciated.
I'd say it's a rewrite, API changes significantly. Maybe you have another logic in mind, which makes all I said above sane.
+1
The problem with current implementation is that I can't put something to flash in multiple places (middlewares). I have to collect it somewhere and put it to flash with this.flash = { ... :(