jaredhanson / connect-flash

Flash message middleware for Connect and Express.
MIT License
1.24k stars 158 forks source link

Passing an object value to req.flash() #29

Closed agarzola closed 8 years ago

agarzola commented 8 years ago

I’m interested in expanding connect-flash to allow passing objects to it. Ideally, I’m looking to do this:

// controller.js

// some other logic happens, then…

// this generates error messages indexed by field name:
var errors = req.validationErrors(true)

if (errors) {
  req.flash('errors', 'Your submission is invalid. See errors below.')
  req.flash(req.validationErrors(true))
  return res.redirect('back')
}

This way, it would be trivial to check for messages.fieldName from my templates like so:

//- template.jade

//- other fields and markup

label(for='fieldName') Field Name:
input(name='fieldName' id='fieldName' class=(messages.fieldName ? 'error' : ''))
if messages.fieldName
  label(for='fieldName').error #{messages.fieldName.msg}

Specifically, I’d like to expand on req.flash() to accept a non-Array object as the second argument or the only argument. Behavior could be as follows:

  1. req.flash('type', object) — Only the object would be registered at req.session.flash.type (i.e. not an array with the passed object as its first item). If an object had already been registered for that type, it would be expanded with the current object’s properties (read: not entirely replaced). If a non-object had already been registered for that type (i.e. req.flash('type', 'A message') followed by req.flash('type', object)), then we would respect the existing array and simply push to it, resulting in req.session.flash.type being equal to [ 'A message', object ].
  2. req.flash(object) — Each key/value pair at the root of the provided object is handled as if it was req.flash(key, value), following existing conventions as well as the new conventions I described above.

I don’t think this would break existing functionality (please correct me if I’m wrong) and it would make more granular error reporting to the user easier to implement.

Is this a contribution you would be interested in, or would you rather it live as a separate project?

jaredhanson commented 8 years ago

This should be implemented as a separate project. The goal of connect-flash is to mimic the functionality in Express 2.x, and nothing else.

agarzola commented 8 years ago

Got it. Thank you for the prompt reply!

loweoj commented 7 years ago

Hey @agarzola, did you make any progress with this?

agarzola commented 7 years ago

@loweoj I think I handled this need some other way last year. That said, if this is something you want to take on yourself, I'd be happy to contribute either with code or testing/reviewing/both.

joshuaetim commented 3 years ago

How I handled mine, the object passed to req.flash can be accessed as the zeroth index

req.flash('old', {me: 'Josh'})
var old = req.flash('old')[0]
res.send(old.me)