presto

Convenience methods added to the response object: renderText, renderJSON and redirect

npm install presto
8 downloads in the last month

Presto

A middleware for connect and flatiron to add some sugar to the reponse object. Inspired by Views, it adds redirect, renderText and renderJSON.

Installation

npm install presto

If you wish to use this as middleware for Flatiron or Connect then you must install and require those libraries individually:

npm install connect

or

npm install flatiron

Usage

Presto can be used as a middleware or a new instance of the Presto class can be initialised should you wish to customise or extend its usage.

Connect

var presto = require('presto').middleware,
    connect = require('connect'),
    http = require('http'),
    app = connect(),
    server;

app.use(presto());
server = http.createServer(app);
server.listen(3000);

server.on('request', function(req, res) {
  if (req.url === '/') {
    res.redirect('http://google.com');
  }
  else if (req.url === '/1') {
    res.renderText('foo');
  }
  else if (req.url === '/2') {
    res.renderJSON({foo: 'bar'});
  }
})

Flatiron

var presto = require('presto').flatiron,
    flatiron = require('flatiron'),
    app = flatiron.createApp();

app.use(flatiron.plugins.http);
app.use(presto());
app.start(3000);

app.router.get('/', function() {
  this.res.renderJSON({foo: 'bar'});
});
app.router.get('/1', function() {
  this.res.renderText('foobar');
});
app.router.get('/2', function() {
  this.res.redirect('http://example.com');
});

Methods

There are 3 methods:

  • redirect(req, res, location, statusCode)
    • location: The URL to redirect to. Can be either a full http URL or a relative/absolute path
    • statusCode: An optional status code. It defaults to 200 so if you wish to do a permanent or temporary redirect you will need to provide 301 or 302 respectively
  • renderText(req, res, text, statusCode)
    • text: A string containing the text to output. The content type will be set to text/plain
    • statusCode: An optional status code. Defaults to 200
  • renderJSON(req, res, data, statusCode)
    • data: A valid object that can be serialised to JSON. The content type will be set to application/json.
    • statusCode: An optional status code. Defaults to 200

When configured as middleware, these methods are bound to the res object and you should use the methods as if the first 2 parameters (req & res) are not there.

npm loves you