Formatters API

Table of Contents

Usage

Restify comes bundled with a selection of useful formatters that prepare your responses for being sent over the wire, but you are free to include your own!

function formatGraphQL(req, res, body) {
    var data = body;
    /* Do a thing to data */
    res.setHeader('Content-Length', Buffer.byteLength(data));
    return data;
}

var server = restify.createServer({
    formatters: {
        'application/graphql': formatGraphQL
    }
});

// Your application now supports content-type 'application/graphql'

Types

formatter

Format a response for being sent over the wire

Type: Function

Parameters

  • req Object the request object (not used)
  • res Object the response object
  • body Object response body to format

Returns String formatted response data

Included formatters

restify comes pre-loaded with a standard set of formatters for common use cases.

formatText

Formats the body to ‘text’ by invoking a toString() on the body if it exists. If it doesn’t, then the response is a zero-length string.

Parameters

  • req Object the request object (not used)
  • res Object the response object
  • body Object response body. If it has a toString() method this will be used to make the string representation

Returns String data

formatJSON

JSON formatter. Will look for a toJson() method on the body. If one does not exist then a JSON.stringify will be attempted.

Parameters

  • req Object the request object (not used)
  • res Object the response object
  • body Object response body

Returns String data

formatJSONP

JSONP formatter. like JSON, but with a callback invocation. Unicode escapes line and paragraph separators.

Parameters

Returns String data

formatBinary

Binary formatter.

Parameters

Returns Buffer body


Improve this page