Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Last active November 7, 2016 07:51
Show Gist options
  • Save nfroidure/43a0eeb06549aeb32dd23c91fa5e0f11 to your computer and use it in GitHub Desktop.
Save nfroidure/43a0eeb06549aeb32dd23c91fa5e0f11 to your computer and use it in GitHub Desktop.
A worflow oriented controller
// No middleware, just pur functions
import getBodyFromReq from 'pureBodyParser';
import getQueryFromReq from 'pureQueryParser';
import sendToRes from 'pureResponseMaker';
// Use dependency injection for required services
// app/config/timer just come from this function caller
module.exports = ({ app, config, timer}) => {
app.post((req, res) => {
// Promise based workflow instead of a middleware chain
// could have been async/await too
Promise.all([
// No surprise, the body comes from the pureBodyParser module
// But i can already guess it allows JSON or YAML
getBodyFromReq.bind(null, req, ['json', 'yaml']),
// And so on for the query
getQueryFromReq.bind(null, req),
])
.then(_buildResponse.bind(null, {timer, config})
// No surprise, the response is sent by the pureResponseMaker module
// But i can already guess it could output JSON or YAML
.sendToRes(sendToRes.bind(null, req, res, ['json', 'yaml'], 200));
});
};
// the pure function that process the request
// could be reused in a completly different context
// a frontend service worker or a websocket server
function _buildResponse({timer, config}, [body, query]) => {
const data = {};
if(query.ms) {
data.when = timer.now();
} else {
data.when = new Date(timer.now()).toISOString();
}
if(config.repeatBody) {
data.body = req.body;
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment