Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Last active Aug 29, 2015
Embed
What would you like to do?
Monadic wrapper for Express API
var express = require('express')
var app = require('./wrapper')(express())
require('./routes')(app)
app.listen(8080)
console.log('Listening on http://localhost:8080')
module.exports = function(app) {
app.get('/', function(req, res) {
return $do {
html <- app.render('index')
return { status: 200, body: html }
}
})
}
var curry = require('core.lambda').curry
var Future = require('data.future')
module.exports = function(app) {
var slice = Function.call.bind([].slice)
var methods = ['get', 'post', 'put', 'delete', 'all']
/**
* Renders the given view `name`.
*
* @method
* @summary String → Object → Future[Error, String]
*/
var _oldRender = app.render
app.render = curry(2, render)
function render(name, options) {
return new Future(function(reject, resolve) {
_oldRender.call( app
, name
, options || {}
, function(error, html) {
if (error) reject(error)
else resolve(html) })})
}
/**
* Handles requests.
*
* @method
* @summary String, Function... → Express
*/
methods.forEach(function(method) {
var original = app[method]
app[method] = function Router(route) {
// `app.get()` is overloaded
if (method === 'get' && arguments.length === 1) return original.call(app, route)
var middlewares = slice(arguments, 1, -1)
var fn = arguments[arguments.length - 1]
var args = [route].concat(middlewares).concat(handler)
original.apply(this, args)
return app
function handler(req, res) {
fn(req, res).fork(handleError(res), send(res)) }
}
})
/**
* Sends some response to the user.
*
* @method
* @summary Response → Contents → Void
*/
send = curry(2, send)
function send(res, contents) {
res.set(contents.headers)
res.send(contents.status || 200, contents.body)
}
/**
* Handles errors.
*
* @method
* @summary Response → Error → Void
*/
handleError = curry(2, handleError)
function handleError(res, error) {
throw error
}
// -- Exports --------------------------------------------------------
return app
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment