koa-flash icon indicating copy to clipboard operation
koa-flash copied to clipboard

This middleware is broken

Open iliakan opened this issue 10 years ago • 4 comments

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

iliakan avatar Apr 14 '15 15:04 iliakan

A constructive pull request would be appreciated.

rickharrison avatar Apr 15 '15 21:04 rickharrison

I'd say it's a rewrite, API changes significantly. Maybe you have another logic in mind, which makes all I said above sane.

iliakan avatar Apr 16 '15 06:04 iliakan

+1

mucsi96 avatar Nov 05 '15 07:11 mucsi96

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 = { ... :(

mucsi96 avatar Nov 05 '15 07:11 mucsi96