cds-snc / node-starter-app

Quick start application setup.... because you have to start somewhere.
MIT License
5 stars 3 forks source link

Presenters! #141

Open jneen opened 4 years ago

jneen commented 4 years ago

Summary

Allowing automatic interpretation of complex data via a function - for example, dates, addresses, etc. (NOTE: Depends on the refactors in the repeater branch). This would not be a breaking change (after the repeater branch).

Motivation

Our session store and forms can only handle very simple JSON data, but often we want to re-use code by wrapping the values in rich objects. These objects may also need access to the request - for example, date objects that contain a locale for month names. While painful to do manually, it is convenient to, for example, register that a particular key is a date, and have that automatically translated in res.locals.

Design Detail

There are a few design kinks to work out, but a presenter is essentially a function that we register to a particular session key. In loadKeys, we would set res.locals[key] = presenters[key](res.locals[key], req, res). This function, unlike customSanitizer from express-validator, is allowed to return a rich object, such as a date or a custom class.

In the case that no presenter is registered for a key, we simply use the original data as-is - so that the default behaviour remains exactly the same.

Drawbacks

This requires saving the "original" data somewhere accessible by views, so that getData still works transparently - res.locals._original or similar.

Prior Art

The presenter pattern is an established pattern for presenting rich data in different contexts.

Unresolved questions