diff --git a/docs/_api/formatters.md b/docs/_api/formatters.md index ea1d1758c..5e4f45440 100644 --- a/docs/_api/formatters.md +++ b/docs/_api/formatters.md @@ -10,11 +10,16 @@ permalink: /docs/formatters-api/ - [Usage][1] - [Types][2] - [formatter][3] -- [Included formatters][4] - - [formatText][5] - - [formatJSON][6] - - [formatJSONP][7] - - [formatBinary][8] + - [Parameters][4] +- [Included formatters][5] + - [formatText][6] + - [Parameters][7] + - [formatJSON][8] + - [Parameters][9] + - [formatJSONP][10] + - [Parameters][11] + - [formatBinary][12] + - [Parameters][13] ## Usage @@ -48,15 +53,15 @@ var server = restify.createServer({ Format a response for being sent over the wire -Type: [Function][9] +Type: [Function][14] -**Parameters** +#### Parameters -- `req` **[Object][10]** the request object (not used) -- `res` **[Object][10]** the response object -- `body` **[Object][10]** response body to format +- `req` **[Object][15]** the request object (not used) +- `res` **[Object][15]** the response object +- `body` **[Object][15]** response body to format -Returns **[String][11]** formatted response data +Returns **[String][16]** formatted response data ## Included formatters @@ -69,52 +74,52 @@ use cases. 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** +#### Parameters -- `req` **[Object][10]** the request object (not used) -- `res` **[Object][10]** the response object -- `body` **[Object][10]** response body. If it has a toString() method this +- `req` **[Object][15]** the request object (not used) +- `res` **[Object][15]** the response object +- `body` **[Object][15]** response body. If it has a toString() method this will be used to make the string representation -Returns **[String][11]** data +Returns **[String][16]** 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** +#### Parameters -- `req` **[Object][10]** the request object (not used) -- `res` **[Object][10]** the response object -- `body` **[Object][10]** response body +- `req` **[Object][15]** the request object (not used) +- `res` **[Object][15]** the response object +- `body` **[Object][15]** response body -Returns **[String][11]** data +Returns **[String][16]** data ### formatJSONP JSONP formatter. like JSON, but with a callback invocation. Unicode escapes line and paragraph separators. -**Parameters** +#### Parameters -- `req` **[Object][10]** the request object -- `res` **[Object][10]** the response object -- `body` **[Object][10]** response body +- `req` **[Object][15]** the request object +- `res` **[Object][15]** the response object +- `body` **[Object][15]** response body -Returns **[String][11]** data +Returns **[String][16]** data ### formatBinary Binary formatter. -**Parameters** +#### Parameters -- `req` **[Object][10]** the request object -- `res` **[Object][10]** the response object -- `body` **[Object][10]** response body +- `req` **[Object][15]** the request object +- `res` **[Object][15]** the response object +- `body` **[Object][15]** response body -Returns **[Buffer][12]** body +Returns **[Buffer][17]** body [1]: #usage @@ -122,20 +127,30 @@ Returns **[Buffer][12]** body [3]: #formatter -[4]: #included-formatters +[4]: #parameters -[5]: #formattext +[5]: #included-formatters -[6]: #formatjson +[6]: #formattext -[7]: #formatjsonp +[7]: #parameters-1 -[8]: #formatbinary +[8]: #formatjson -[9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function +[9]: #parameters-2 -[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[10]: #formatjsonp -[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[11]: #parameters-3 -[12]: https://nodejs.org/api/buffer.html +[12]: #formatbinary + +[13]: #parameters-4 + +[14]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function + +[15]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object + +[16]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String + +[17]: https://nodejs.org/api/buffer.html diff --git a/docs/_api/plugins.md b/docs/_api/plugins.md index e8c0c4e6b..5df4aefaf 100644 --- a/docs/_api/plugins.md +++ b/docs/_api/plugins.md @@ -10,37 +10,79 @@ permalink: /docs/plugins-api/ - [Usage][1] - [server.pre() plugins][2] - [context][3] - - [dedupeSlashes][4] - - [pause][5] - - [sanitizePath][6] - - [reqIdHeaders][7] - - [strictQueryParams][8] - - [userAgentConnection][9] -- [server.use() plugins][10] - - [acceptParser][11] - - [authorizationParser][12] - - [dateParser][13] - - [queryParser][14] - - [jsonp][15] - - [bodyParser][16] - - [requestLogger][17] - - [gzipResponse][18] - - [serveStatic][19] - - [serveStaticFiles][20] - - [throttle][21] - - [requestExpiry][22] - - [Using an external storage mechanism for key/bucket mappings.][23] - - [inflightRequestThrottle][24] - - [cpuUsageThrottle][25] - - [conditionalHandler][26] - - [conditionalRequest][27] - - [auditLogger][28] - - [metrics][29] -- [Types][30] - - [metrics~callback][31] -- [req.set][32] -- [req.get][33] -- [req.getAll][34] + - [Examples][4] + - [dedupeSlashes][5] + - [Examples][6] + - [pause][7] + - [sanitizePath][8] + - [reqIdHeaders][9] + - [Parameters][10] + - [strictQueryParams][11] + - [Parameters][12] + - [userAgentConnection][13] + - [Parameters][14] +- [server.use() plugins][15] + - [acceptParser][16] + - [Parameters][17] + - [Examples][18] + - [authorizationParser][19] + - [Parameters][20] + - [Examples][21] + - [dateParser][22] + - [Parameters][23] + - [Examples][24] + - [queryParser][25] + - [Parameters][26] + - [Examples][27] + - [jsonp][28] + - [Examples][29] + - [bodyParser][30] + - [Parameters][31] + - [Examples][32] + - [requestLogger][33] + - [Parameters][34] + - [Examples][35] + - [gzipResponse][36] + - [Parameters][37] + - [Examples][38] + - [serveStatic][39] + - [Parameters][40] + - [Examples][41] + - [serveStaticFiles][42] + - [Parameters][43] + - [Examples][44] + - [throttle][45] + - [Parameters][46] + - [Examples][47] + - [requestExpiry][48] + - [Using an external storage mechanism for key/bucket mappings.][49] + - [Parameters][50] + - [Examples][51] + - [inflightRequestThrottle][52] + - [Parameters][53] + - [Examples][54] + - [cpuUsageThrottle][55] + - [Parameters][56] + - [Examples][57] + - [conditionalHandler][58] + - [Parameters][59] + - [Examples][60] + - [conditionalRequest][61] + - [Examples][62] + - [auditLogger][63] + - [Parameters][64] + - [Examples][65] + - [metrics][66] + - [Parameters][67] + - [Examples][68] +- [Types][69] + - [metrics~callback][70] + - [Parameters][71] +- [req.set][72] + - [Parameters][73] +- [req.get][74] + - [Parameters][75] +- [req.getAll][76] ## Usage @@ -84,7 +126,7 @@ method. This plugin creates `req.set(key, val)` and `req.get(key)` methods for setting and retrieving request specific data. -**Examples** +#### Examples ```javascript server.pre(restify.plugins.pre.context()); @@ -100,14 +142,14 @@ server.get('/', [ ]); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### dedupeSlashes This plugin deduplicates extra slashes found in the URL. This can help with malformed URLs that might otherwise get misrouted. -**Examples** +#### Examples ```javascript server.pre(restify.plugins.pre.dedupeSlashes()); @@ -119,24 +161,24 @@ server.get('/hello/:one', function(req, res, next) { // the server will now convert requests to /hello//jake => /hello/jake ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### pause This pre handler fixes issues with node hanging when an `asyncHandler` is used prior to `bodyParser`. -[https://github.com/restify/node-restify/issues/287][36] -[https://github.com/restify/node-restify/issues/409][37] -[https://github.com/restify/node-restify/wiki/1.4-to-2.0-Migration-Tips][38] +[https://github.com/restify/node-restify/issues/287][78] +[https://github.com/restify/node-restify/issues/409][79] +[https://github.com/restify/node-restify/wiki/1.4-to-2.0-Migration-Tips][80] -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### sanitizePath Cleans up sloppy URLs on the request object, like `/foo////bar///` to `/foo/bar`. -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### reqIdHeaders @@ -144,14 +186,14 @@ This plugin pulls the value from an incoming request header and uses it as the value of the request id. Subsequent calls to `req.id()` will return the header values. -**Parameters** +#### Parameters -- `opts` **[Object][39]** an options object - - `opts.headers` **[Array][40]<[String][41]>** array of headers from where to pull existing +- `opts` **[Object][81]** an options object + - `opts.headers` **[Array][82]<[String][83]>** array of headers from where to pull existing request id headers. Lookup precedence is left to right (lowest index first) -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### strictQueryParams @@ -167,14 +209,14 @@ with an appropriate status code. part of Hypertext Transfer Protocol -- HTTP/1.1 | 5.1.2 Request-URI RFC 2616 Fielding, et al. -**Parameters** +#### Parameters -- `options` **[Object][39]?** an options object - - `options.message` **[String][41]?** a custom error message +- `options` **[Object][81]?** an options object + - `options.message` **[String][83]?** a custom error message default value: "Url query params does not meet strict format" -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### userAgentConnection @@ -191,13 +233,13 @@ curl does not). To be slightly more generic, the options block takes a user agent regexp, however. -**Parameters** +#### Parameters -- `options` **[Object][39]?** an options object - - `options.userAgentRegExp` **[RegExp][42]** matching any +- `options` **[Object][81]?** an options object + - `options.userAgentRegExp` **[RegExp][84]** matching any user-agents applicable (optional, default `/^curl.+/`) -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ## server.use() plugins @@ -215,11 +257,11 @@ for a non-handled type, this plugin will return a `NotAcceptableError` (406). Note you can get the set of types allowed from a restify server by doing `server.acceptable`. -**Parameters** +#### Parameters -- `accepts` **[Array][40]<[String][41]>** array of accept types. +- `accepts` **[Array][82]<[String][83]>** array of accept types. -**Examples** +#### Examples ```javascript server.use(restify.plugins.acceptParser(server.acceptable)); @@ -227,21 +269,21 @@ server.use(restify.plugins.acceptParser(server.acceptable)); - Throws **NotAcceptableError** -Returns **[Function][35]** restify handler. +Returns **[Function][77]** restify handler. ### authorizationParser Parses out the `Authorization` header as best restify can. Currently only HTTP Basic Auth and -[HTTP Signature][43] +[HTTP Signature][85] schemes are supported. -**Parameters** +#### Parameters -- `options` **[Object][39]?** an optional options object that is +- `options` **[Object][81]?** an optional options object that is passed to http-signature -**Examples** +#### Examples Subsequent handlers will see `req.authorization`, which looks like above. @@ -263,7 +305,7 @@ is unrecognized, the only thing available in `req.authorization` will be - Throws **InvalidArgumentError** -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### dateParser @@ -276,11 +318,11 @@ before (`$now - $clockSkew`). The default clockSkew allowance is 5m (thanks Kerberos!) -**Parameters** +#### Parameters -- `clockSkew` **[Number][44]** allowed clock skew in seconds. (optional, default `300`) +- `clockSkew` **[Number][86]** allowed clock skew in seconds. (optional, default `300`) -**Examples** +#### Examples ```javascript // Allows clock skew of 1m @@ -290,7 +332,7 @@ server.use(restify.plugins.dateParser(60)); - Throws **RequestExpiredError** - Throws **InvalidHeaderError** -Returns **[Function][35]** restify handler. +Returns **[Function][77]** restify handler. ### queryParser @@ -300,41 +342,44 @@ additionally params are merged into `req.params`. You can disable by passing in `mapParams: false` in the options object. Many options correspond directly to option defined for the underlying -[`qs.parse`][45]. +[`qs.parse`][87]. -**Parameters** +#### Parameters -- `options` **[Object][39]?** an options object - - `options.mapParams` **[Object][39]** disable passing (optional, default `true`) - - `options.mapParams` **[Boolean][46]** Copies parsed query parameters +- `options` **[Object][81]?** an options object + - `options.mapParams` **[Object][81]** disable passing (optional, default `true`) + - `options.mapParams` **[Boolean][88]** Copies parsed query parameters into`req.params`. (optional, default `false`) - - `options.overrideParams` **[Boolean][46]** Only applies when if + - `options.overrideParams` **[Boolean][88]** Only applies when if mapParams true. When true, will stomp on req.params field when existing value is found. (optional, default `false`) - - `options.allowDots` **[Boolean][46]** Transform `?foo.bar=baz` to a + - `options.allowDots` **[Boolean][88]** Transform `?foo.bar=baz` to a nested object: `{foo: {bar: 'baz'}}`. (optional, default `false`) - - `options.arrayLimit` **[Number][44]** Only transform `?a[$index]=b` + - `options.arrayLimit` **[Number][86]** Only transform `?a[$index]=b` to an array if `$index` is less than `arrayLimit`. (optional, default `20`) - - `options.depth` **[Number][44]** The depth limit for parsing + - `options.depth` **[Number][86]** The depth limit for parsing nested objects, e.g. `?a[b][c][d][e][f][g][h][i]=j`. (optional, default `5`) - - `options.parameterLimit` **[Number][44]** Maximum number of query + - `options.parameterLimit` **[Number][86]** Maximum number of query params parsed. Additional params are silently dropped. (optional, default `1000`) - - `options.parseArrays` **[Boolean][46]** Whether to parse + - `options.parseArrays` **[Boolean][88]** Whether to parse `?a[]=b&a[1]=c` to an array, e.g. `{a: ['b', 'c']}`. (optional, default `true`) - - `options.plainObjects` **[Boolean][46]** Whether `req.query` is a + - `options.plainObjects` **[Boolean][88]** Whether `req.query` is a "plain" object -- does not inherit from `Object`. This can be used to allow query params whose names collide with Object methods, e.g. `?hasOwnProperty=blah`. (optional, default `false`) - - `options.strictNullHandling` **[Boolean][46]** If true, `?a&b=` + - `options.strictNullHandling` **[Boolean][88]** If true, `?a&b=` results in `{a: null, b: ''}`. Otherwise, `{a: '', b: ''}`. (optional, default `false`) + - `options.throwOnLimitExceeded` **[Boolean][88]** If true, throws + (surfaced as a `InvalidContentError`) when `arrayLimit` or `parameterLimit` + is exceeded, instead of silently dropping the offending params. (optional, default `false`) -**Examples** +#### Examples ```javascript server.use(restify.plugins.queryParser({ mapParams: false })); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### jsonp @@ -346,14 +391,14 @@ There is also a default `application/javascript` formatter to handle this. You _should_ set the `queryParser` plugin to run before this, but if you don't this plugin will still parse the query string properly. -**Examples** +#### Examples ```javascript var server = restify.createServer(); server.use(restify.plugins.jsonp()); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### bodyParser @@ -377,65 +422,71 @@ All bodyParsers support the following options: mapParams true. when true, will stomp on req.params value when existing value is found. -**Parameters** +#### Parameters -- `options` **[Object][39]?** an option object - - `options.maxBodySize` **[Number][44]?** The maximum size in bytes allowed in +- `options` **[Object][81]?** an option object + - `options.maxBodySize` **[Number][86]?** The maximum size in bytes allowed in the HTTP body. Useful for limiting clients from hogging server memory. - - `options.mapParams` **[Boolean][46]?** if `req.params` should be filled with + - `options.mapParams` **[Boolean][88]?** if `req.params` should be filled with parsed parameters from HTTP body. - - `options.mapFiles` **[Boolean][46]?** if `req.params` should be filled with + - `options.mapFiles` **[Boolean][88]?** if `req.params` should be filled with the contents of files sent through a multipart request. - [formidable][47] is used internally + [formidable][89] is used internally for parsing, and a file is denoted as a multipart part with the `filename` option set in its `Content-Disposition`. This will only be performed if `mapParams` is true. - - `options.overrideParams` **[Boolean][46]?** if an entry in `req.params` + - `options.overrideParams` **[Boolean][88]?** if an entry in `req.params` should be overwritten by the value in the body if the names are the same. For instance, if you have the route `/:someval`, and someone posts an `x-www-form-urlencoded` Content-Type with the body `someval=happy` to `/sad`, the value will be `happy` if `overrideParams` is `true`, `sad` otherwise. - - `options.multipartHandler` **[Function][35]?** a callback to handle any + - `options.multipartHandler` **[Function][77]?** a callback to handle any multipart part which is not a file. If this is omitted, the default handler is invoked which may or may not map the parts into `req.params`, depending on the `mapParams`-option. - - `options.multipartFileHandler` **[Function][35]?** a callback to handle any + - `options.multipartFileHandler` **[Function][77]?** a callback to handle any multipart file. It will be a file if the part has a `Content-Disposition` with the `filename` parameter set. This typically happens when a browser sends a form and there is a parameter similar to ``. If this is not provided, the default behaviour is to map the contents into `req.params`. - - `options.keepExtensions` **[Boolean][46]?** if you want the uploaded + - `options.keepExtensions` **[Boolean][88]?** if you want the uploaded files to include the extensions of the original files (multipart uploads only). Does nothing if `multipartFileHandler` is defined. - - `options.uploadDir` **[String][41]?** Where uploaded files are + - `options.uploadDir` **[String][83]?** Where uploaded files are intermediately stored during transfer before the contents is mapped into `req.params`. Does nothing if `multipartFileHandler` is defined. - - `options.multiples` **[Boolean][46]?** if you want to support html5 multiple + - `options.multiples` **[Boolean][88]?** if you want to support html5 multiple attribute in upload fields. - - `options.hash` **[String][41]?** If you want checksums calculated for + - `options.hash` **[String][83]?** If you want checksums calculated for incoming files, set this to either `sha1` or `md5`. - - `options.rejectUnknown` **[Boolean][46]?** Set to `true` if you want to end + - `options.rejectUnknown` **[Boolean][88]?** Set to `true` if you want to end the request with a `UnsupportedMediaTypeError` when none of the supported content types was given. - - `options.requestBodyOnGet` **[Boolean][46]** Parse body of a GET + - `options.requestBodyOnGet` **[Boolean][88]** Parse body of a GET request. (optional, default `false`) - - `options.reviver` **[Function][35]?** `jsonParser` only. If a function, + - `options.reviver` **[Function][77]?** `jsonParser` only. If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. For more information check out `JSON.parse(text[, reviver])`. - - `options.maxFieldsSize` **[Number][44]** `multipartParser` + - `options.maxFieldsSize` **[Number][86]** `multipartParser` only. Limits the amount of memory all fields together (except files) can allocate in bytes. The default size is `2 * 1024 * 1024` bytes _(2MB)_. (optional, default `2*1024*1024`) + - `options.arrayLimit` **[Number][86]** `urlEncodedBodyParser` only. Only + transform `a[$index]=b` to an array if `$index` is less than `arrayLimit`. (optional, default `20`) + - `options.throwOnLimitExceeded` **[Boolean][88]** `urlEncodedBodyParser` + only. If true, throws when `arrayLimit` or `parameterLimit` is exceeded, + instead of silently dropping the offending params. The error is surfaced + as an `InvalidContentError`. (optional, default `false`) -**Examples** +#### Examples ```javascript server.use(restify.plugins.bodyParser({ @@ -466,28 +517,33 @@ server.use(restify.plugins.bodyParser({ - Throws **UnsupportedMediaTypeError** -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### requestLogger -Sets up a child [bunyan][48] logger with +Sets up a child [logger][90] logger with the current request id filled in, along with any other parameters you define. You can pass in no options to this, in which case only the request id will be appended, and no serializers appended (this is also the most performant); the logger created at server creation time will be used as the parent logger. -This logger can be used normally, with [req.log][49]. +This logger can be used normally, with [req.log][91]. This plugin does _not_ log each individual request. Use the Audit Logging plugin or a custom middleware for that use. -**Parameters** +#### Parameters -- `options` **[Object][39]?** an options object - - `options.headers` **[Array][40]?** A list of headers to transfer from +- `options` **[Object][81]?** an options object + - `options.headers` **[Array][82]?** A list of headers to transfer from the request to top level props on the log. + - `options.properties` **[Object][81]?** A set of key-values to pass to the child logger + - `options.serializers` **[Object][81]?** Override serializers to use in the child logger + - `options.log` **[Object][81]?** A logger to use as a fallback if req.log is missing + - `options.requestIdFieldName` **[String][83]?** The name of the request id property attached + to log lines. Defaults to "req_id". -**Examples** +#### Examples ```javascript server.use(restify.plugins.requestLogger({ @@ -498,7 +554,7 @@ server.use(restify.plugins.requestLogger({ })); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### gzipResponse @@ -514,29 +570,29 @@ that the `content-length` header cannot be known, and so This plugin has no impact if the client does not send `accept-encoding: gzip`. -[https://github.com/restify/node-restify/issues/284][50] +[https://github.com/restify/node-restify/issues/284][92] -**Parameters** +#### Parameters -- `opts` **[Object][39]?** an options object, see: zlib.createGzip +- `opts` **[Object][81]?** an options object, see: zlib.createGzip -**Examples** +#### Examples ```javascript server.use(restify.plugins.gzipResponse()); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### serveStatic Serves static files. -**Parameters** +#### Parameters -- `options` **[Object][39]** an options object +- `options` **[Object][81]** an options object -**Examples** +#### Examples The serveStatic module is different than most of the other plugins, in that it is expected that you are going to map it to a route, as below: @@ -591,26 +647,26 @@ server.get('/home/([a-z]+[.]html)', restify.plugins.serveStatic({ - Throws **NotAuthorizedError** - Throws **ResourceNotFoundError** -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### serveStaticFiles Serves static files, with API similar to expressjs -**Parameters** +#### Parameters -- `directory` **[String][41]** the directory to serve files from -- `opts` **[Object][39]** an options object, which is optional - - `opts.maxAge` **[Number][44]** specify max age in millisecs (optional, default `0`) - - `opts.etag` **[Boolean][46]** enable/disable etag, default = true (optional, default `true`) - - `opts.setHeaders` **[Function][35]?** set custom headers for the Files +- `directory` **[String][83]** the directory to serve files from +- `opts` **[Object][81]** an options object, which is optional + - `opts.maxAge` **[Number][86]** specify max age in millisecs (optional, default `0`) + - `opts.etag` **[Boolean][88]** enable/disable etag, default = true (optional, default `true`) + - `opts.setHeaders` **[Function][77]?** set custom headers for the Files (synchronously), The function is called as `fn(res, path, stat)`, where the arguments are: `res` the response object `path` the file path that is being sent `stat` the stat object of the file that is being sent -**Examples** +#### Examples The serveStaticFiles plugin allows you to map a GET route to a directory on the disk @@ -626,7 +682,7 @@ The GET `route` and `directory` combination will serve a file located in `./documentation/v1/index.html` when you attempt to hit `http://localhost:8080/public/index.html` -The plugin uses [send][51] under the hood +The plugin uses [send][93] under the hood which is also used by `expressjs` to serve static files. Most of the options that work with `send` will work with this plugin. @@ -649,7 +705,7 @@ server.get('/public/*', - Throws **NotAuthorizedError** - Throws **ResourceNotFoundError** -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### throttle @@ -657,7 +713,7 @@ Creates an API rate limiter that can be plugged into the standard restify request handling pipeline. `restify` ships with a fairly comprehensive implementation of -[Token bucket][52], with the ability +[Token bucket][94], with the ability to throttle on IP (or x-forwarded-for) and username (from `req.username`). You define "global" request rate and burst rate, and you can define overrides for specific keys. @@ -668,7 +724,7 @@ than `/my/fast/memcache`). If a client has consumed all of their available rate/burst, an HTTP response code of `429` -[Too Many Requests][53] +[Too Many Requests][95] is returned. This throttle gives you three options on which to throttle: @@ -688,28 +744,28 @@ TokenBucket to track each. On the `options` object ip and username are treated as an XOR. -**Parameters** +#### Parameters -- `options` **[Object][39]** required options with: - - `options.burst` **[Number][44]** burst - - `options.rate` **[Number][44]** rate - - `options.ip` **[Boolean][46]?** ip - - `options.username` **[Boolean][46]?** username - - `options.xff` **[Boolean][46]?** xff - - `options.setHeaders` **[Boolean][46]** Set response headers for rate, +- `options` **[Object][81]** required options with: + - `options.burst` **[Number][86]** burst + - `options.rate` **[Number][86]** rate + - `options.ip` **[Boolean][88]?** ip + - `options.username` **[Boolean][88]?** username + - `options.xff` **[Boolean][88]?** xff + - `options.setHeaders` **[Boolean][88]** Set response headers for rate, limit (burst) and remaining. (optional, default `false`) - - `options.overrides` **[Object][39]?** overrides - - `options.tokensTable` **[Object][39]** a storage engine this plugin will + - `options.overrides` **[Object][81]?** overrides + - `options.tokensTable` **[Object][81]** a storage engine this plugin will use to store throttling keys -> bucket mappings. If you don't specify this, the default is to use an in-memory O(1) LRU, with 10k distinct keys. Any implementation just needs to support put/get. - - `options.maxKeys` **[Number][44]** If using the default + - `options.maxKeys` **[Number][86]** If using the default implementation, you can specify how large you want the table to be. (optional, default `10000`) -**Examples** +#### Examples An example options object with overrides: @@ -729,7 +785,7 @@ An example options object with overrides: - Throws **TooManyRequestsError** -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### requestExpiry @@ -767,18 +823,18 @@ and/or uniform request distribution. To enable this, you can pass in `options.tokensTable`, which is simply any Object that supports `put` and `get` with a `String` key, and an `Object` value. -**Parameters** +#### Parameters -- `opts` **[Object][39]** an options object - - `opts.absoluteHeader` **[String][41]?** The header key to be used for +- `opts` **[Object][81]** an options object + - `opts.absoluteHeader` **[String][83]?** The header key to be used for the expiry time of each request. - - `opts.startHeader` **[String][41]** The header key for the start time + - `opts.startHeader` **[String][83]** The header key for the start time of the request. - - `opts.timeoutHeader` **[String][41]** The header key for the time in + - `opts.timeoutHeader` **[String][83]** The header key for the time in milliseconds that should ellapse before the request is considered expired. -**Examples** +#### Examples The only option provided is `header` which is the request header used to specify the client timeout. @@ -790,7 +846,7 @@ server.use(restify.plugins.requestExpiry({ }); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### inflightRequestThrottle @@ -806,17 +862,17 @@ requests. It defaults to `503 ServiceUnavailableError`. This plugin should be registered as early as possibly in the middleware stack using `pre` to avoid performing unnecessary work. -**Parameters** +#### Parameters -- `opts` **[Object][39]** configure this plugin - - `opts.limit` **[Number][44]** maximum number of inflight requests the server +- `opts` **[Object][81]** configure this plugin + - `opts.limit` **[Number][86]** maximum number of inflight requests the server will handle before returning an error - - `opts.err` **[Error][54]** A restify error used as a response when the + - `opts.err` **[Error][96]** A restify error used as a response when the inflight request limit is exceeded - - `opts.server` **[Function][35]** the instance of the restify server this + - `opts.server` **[Function][77]** the instance of the restify server this plugin will throttle. -**Examples** +#### Examples ```javascript var errors = require('restify-errors'); @@ -828,7 +884,7 @@ options.res = new errors.InternalServerError(); server.pre(restify.plugins.inflightRequestThrottle(options)); ``` -Returns **[Function][35]** middleware to be registered on server.pre +Returns **[Function][77]** middleware to be registered on server.pre ### cpuUsageThrottle @@ -872,20 +928,20 @@ case. For a better understanding of the EWMA algorithn, refer to the documentation for the ewma module. -**Parameters** +#### Parameters -- `opts` **[Object][39]** Configure this plugin. - - `opts.limit` **[Number][44]?** The point at which restify will begin +- `opts` **[Object][81]** Configure this plugin. + - `opts.limit` **[Number][86]?** The point at which restify will begin rejecting a % of all requests at the front door. This value is a percentage. For example 0.8 === 80% average CPU utilization. Defaults to 0.75. - - `opts.max` **[Number][44]?** The point at which restify will reject 100% of + - `opts.max` **[Number][86]?** The point at which restify will reject 100% of all requests at the front door. This is used in conjunction with limit to determine what % of traffic restify needs to reject when attempting to bring the average load back to the user requested values. Since Node.js is single threaded, the default for this is 1. In some rare cases, a Node.js process can exceed 100% CPU usage and you will want to update this value. - - `opts.interval` **[Number][44]?** How frequently we calculate the average CPU + - `opts.interval` **[Number][86]?** How frequently we calculate the average CPU utilization. When we calculate an average CPU utilization, we calculate it over this interval, and this drives whether or not we should be shedding load. This can be thought of as a "resolution" where the lower this value, @@ -893,7 +949,7 @@ for the ewma module. we will recalculate the % of traffic we should be shedding. This check is rather lightweight, while the default is 250ms, you should be able to decrease this value without seeing a significant impact to performance. - - `opts.halfLife` **[Number][44]?** When we sample the CPU usage on an + - `opts.halfLife` **[Number][86]?** When we sample the CPU usage on an interval, we create a series of data points. We take these points and calculate a moving average. The halfLife indicates how quickly a point "decays" to @@ -904,7 +960,7 @@ for the ewma module. determininng whether it should shed load, set this to a higher value. The unit is in ms. Defaults to 250. -**Examples** +#### Examples ```javascript var restify = require('restify'); @@ -931,20 +987,20 @@ server.pre(plugin); plugin.update({ limit: .4, halfLife: 5000 }); ``` -Returns **[Function][35]** middleware to be registered on server.pre +Returns **[Function][77]** middleware to be registered on server.pre ### conditionalHandler Runs first handler that matches to the condition -**Parameters** +#### Parameters -- `candidates` **([Object][39] \| [Array][40]<[Object][39]>)** candidates - - `candidates.handler` **([Function][35] \| [Array][40]<[Function][35]>)** handler(s) - - `candidates.version` **([String][41] \| [Array][40]<[String][41]>)?** '1.1.0', ['1.1.0', '1.2.0'] - - `candidates.contentType` **[String][41]?** accepted content type, '\*\\/json' +- `candidates` **([Object][81] \| [Array][82]<[Object][81]>)** candidates + - `candidates.handler` **([Function][77] \| [Array][82]<[Function][77]>)** handler(s) + - `candidates.version` **([String][83] \| [Array][82]<[String][83]>)?** '1.1.0', ['1.1.0', '1.2.0'] + - `candidates.contentType` **[String][83]?** accepted content type, '\*\\/json' -**Examples** +#### Examples ```javascript server.use(restify.plugins.conditionalHandler({ @@ -991,7 +1047,7 @@ server.get('/hello/:name', restify.plugins.conditionalHandler([ - Throws **InvalidVersionError** - Throws **UnsupportedMediaTypeError** -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### conditionalRequest @@ -1016,7 +1072,7 @@ The specific headers this plugin looks at are: - `If-Modified-Since` - `If-Unmodified-Since` -**Examples** +#### Examples ```javascript server.use(restify.plugins.conditionalRequest()); @@ -1038,29 +1094,31 @@ server.get('/hello/:name', function(req, res, next) { - Throws **BadRequestError** - Throws **PreconditionFailedError** -Returns **[Array][40]<[Function][35]>** Handlers +Returns **[Array][82]<[Function][77]>** Handlers ### auditLogger -**Parameters** +#### Parameters -- `opts` **[Object][39]** The options object. - - `opts.log` **[Object][39]** The logger. - - `opts.event` **[String][41]** The event from the server which initiates the +- `opts` **[Object][81]** The options object. + - `opts.log` **[Object][81]** The logger. + - `opts.event` **[String][83]** The event from the server which initiates the log, one of 'pre', 'routed', or 'after' - - `opts.context` **[Function][35]?** The optional context function of signature + - `opts.context` **[Function][77]?** The optional context function of signature f(req, res, route, err). Invoked each time an audit log is generated. This function can return an object that customizes the format of anything off the req, res, route, and err objects. The output of this function will be available on the `context` key in the audit object. - - `opts.server` **[Object][39]?** The restify server, used to emit + - `opts.server` **[Object][81]?** The restify server, used to emit the audit log object programmatically - - `opts.printLog` **[boolean][46]** Whether to print the log + - `opts.printLog` **[boolean][88]** Whether to print the log via the logger. (optional, default `true`) - - `opts.serializers` **[Object][39]?** Override the default logger serializers + - `opts.serializers` **[Object][81]?** Override the default logger serializers for err, req and res + - `opts.requestIdFieldName` **[String][83]?** The name of the request id property attached + to log lines. Defaults to "req_id". -**Examples** +#### Examples Audit logging is a special plugin, as you don't use it with `.use()` but with the `after` event: @@ -1068,10 +1126,10 @@ but with the `after` event: ```javascript server.on('after', restify.plugins.auditLogger({ - log: bunyan.createLogger({ - name: 'audit', - stream: process.stdout - }), + log: pino( + {name: 'audit'}, + process.stdout + ), event: 'after', server: SERVER, logMetrics : logBuffer, @@ -1079,7 +1137,7 @@ server.on('after', restify.plugins.auditLogger({ })); ``` -You pass in the auditor a bunyan logger, optionally server object, +You pass in the auditor a pino logger, optionally server object, Ringbuffer and a flag printLog indicate if log needs to be print out at info level or not. By default, without specify printLog flag, it will write out record lookling like this: @@ -1110,7 +1168,7 @@ record lookling like this: "trailers": {}, "version": "*", "timers": { - "bunyan": 52, + "requestLogger": 52, "saveAction": 8, "reqResTracker": 213, "addContext": 8, @@ -1166,8 +1224,8 @@ The `timers` field shows the time each handler took to run in microseconds. Restify by default will record this information for every handler for each route. However, if you decide to include nested handlers, you can track the timing yourself by utilizing the Request -[startHandlerTimer][55] and -[endHandlerTimer][56] API. +[startHandlerTimer][97] and +[endHandlerTimer][98] API. You can also listen to auditlog event and get same above log object when log event emits. For example @@ -1178,7 +1236,7 @@ SERVER.on('auditlog', function (data) { }); ``` -Returns **[Function][35]** Handler +Returns **[Function][77]** Handler ### metrics @@ -1188,13 +1246,13 @@ event, e.g., `server.on('after', restify.plugins.metrics());`: A plugin that listens to the server's after event and emits information about that request. -**Parameters** +#### Parameters -- `opts` **[Object][39]** an options obj +- `opts` **[Object][81]** an options obj - `opts.server` **Server** restify server - `callback` **createMetrics~callback** a callback fn -**Examples** +#### Examples ```javascript server.on('after', restify.plugins.metrics({ server: server }, @@ -1203,7 +1261,7 @@ server.on('after', restify.plugins.metrics({ server: server }, })); ``` -Returns **[Function][35]** returns a function suitable to be used +Returns **[Function][77]** returns a function suitable to be used with restify server's `after` event ## Types @@ -1215,33 +1273,33 @@ Returns **[Function][35]** returns a function suitable to be used Callback used by metrics plugin -Type: [Function][35] +Type: [Function][77] -**Parameters** +#### Parameters -- `err` **[Error][54]** -- `metrics` **[Object][39]** metrics about the request - - `metrics.statusCode` **[Number][44]** status code of the response. can be +- `err` **[Error][96]** +- `metrics` **[Object][81]** metrics about the request + - `metrics.statusCode` **[Number][86]** status code of the response. can be undefined in the case of an uncaughtException - - `metrics.method` **[String][41]** http request verb - - `metrics.totalLatency` **[Number][44]** latency includes both request is flushed + - `metrics.method` **[String][83]** http request verb + - `metrics.totalLatency` **[Number][86]** latency includes both request is flushed and all handlers finished - - `metrics.latency` **[Number][44]** latency when request is flushed - - `metrics.preLatency` **([Number][44] | null)** pre handlers latency - - `metrics.useLatency` **([Number][44] | null)** use handlers latency - - `metrics.routeLatency` **([Number][44] | null)** route handlers latency - - `metrics.path` **[String][41]** `req.path()` value - - `metrics.inflightRequests` **[Number][44]** Number of inflight requests pending + - `metrics.latency` **[Number][86]** latency when request is flushed + - `metrics.preLatency` **([Number][86] | null)** pre handlers latency + - `metrics.useLatency` **([Number][86] | null)** use handlers latency + - `metrics.routeLatency` **([Number][86] | null)** route handlers latency + - `metrics.path` **[String][83]** `req.path()` value + - `metrics.inflightRequests` **[Number][86]** Number of inflight requests pending in restify. - - `metrics.unifinishedRequests` **[Number][44]** Same as `inflightRequests` - - `metrics.connectionState` **[String][41]** can be either `'close'` or + - `metrics.unifinishedRequests` **[Number][86]** Same as `inflightRequests` + - `metrics.connectionState` **[String][83]** can be either `'close'` or `undefined`. If this value is set, err will be a corresponding `RequestCloseError`. If connectionState is either `'close'`, then the `statusCode` is not applicable since the connection was severed before a response was written. -- `req` **[Request][57]** the request obj -- `res` **[Response][58]** the response obj +- `req` **[Request][99]** the request obj +- `res` **[Response][100]** the response obj - `route` **Route** the route obj that serviced the request ## req.set @@ -1249,21 +1307,21 @@ Type: [Function][35] Set context value by key Requires the context plugin. -**Parameters** +### Parameters -- `key` **[String][41]** key +- `key` **[String][83]** key - `value` **any** value -Returns **[undefined][59]** no return value +Returns **[undefined][101]** no return value ## req.get Get context value by key. Requires the context plugin. -**Parameters** +### Parameters -- `key` **[String][41]** key +- `key` **[String][83]** key Returns **any** value stored in context @@ -1280,114 +1338,198 @@ Returns **any** value stored in context [3]: #context -[4]: #dedupeslashes +[4]: #examples -[5]: #pause +[5]: #dedupeslashes -[6]: #sanitizepath +[6]: #examples-1 -[7]: #reqidheaders +[7]: #pause -[8]: #strictqueryparams +[8]: #sanitizepath -[9]: #useragentconnection +[9]: #reqidheaders -[10]: #serveruse-plugins +[10]: #parameters -[11]: #acceptparser +[11]: #strictqueryparams -[12]: #authorizationparser +[12]: #parameters-1 -[13]: #dateparser +[13]: #useragentconnection -[14]: #queryparser +[14]: #parameters-2 -[15]: #jsonp +[15]: #serveruse-plugins -[16]: #bodyparser +[16]: #acceptparser -[17]: #requestlogger +[17]: #parameters-3 -[18]: #gzipresponse +[18]: #examples-2 -[19]: #servestatic +[19]: #authorizationparser -[20]: #servestaticfiles +[20]: #parameters-4 -[21]: #throttle +[21]: #examples-3 -[22]: #requestexpiry +[22]: #dateparser -[23]: #using-an-external-storage-mechanism-for-keybucket-mappings +[23]: #parameters-5 -[24]: #inflightrequestthrottle +[24]: #examples-4 -[25]: #cpuusagethrottle +[25]: #queryparser -[26]: #conditionalhandler +[26]: #parameters-6 -[27]: #conditionalrequest +[27]: #examples-5 -[28]: #auditlogger +[28]: #jsonp -[29]: #metrics +[29]: #examples-6 -[30]: #types +[30]: #bodyparser -[31]: #metricscallback +[31]: #parameters-7 -[32]: #reqset +[32]: #examples-7 -[33]: #reqget +[33]: #requestlogger -[34]: #reqgetall +[34]: #parameters-8 -[35]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function +[35]: #examples-8 -[36]: https://github.com/restify/node-restify/issues/287 +[36]: #gzipresponse -[37]: https://github.com/restify/node-restify/issues/409 +[37]: #parameters-9 -[38]: https://github.com/restify/node-restify/wiki/1.4-to-2.0-Migration-Tips +[38]: #examples-9 -[39]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[39]: #servestatic -[40]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[40]: #parameters-10 -[41]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[41]: #examples-10 -[42]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp +[42]: #servestaticfiles -[43]: https://github.com/joyent/node-http-signature +[43]: #parameters-11 -[44]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number +[44]: #examples-11 -[45]: https://github.com/ljharb/qs +[45]: #throttle -[46]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[46]: #parameters-12 -[47]: https://github.com/felixge/node-formidable +[47]: #examples-12 -[48]: https://github.com/trentm/node-bunyan +[48]: #requestexpiry -[49]: #request-api +[49]: #using-an-external-storage-mechanism-for-keybucket-mappings -[50]: https://github.com/restify/node-restify/issues/284 +[50]: #parameters-13 -[51]: https://github.com/pillarjs/send +[51]: #examples-13 -[52]: http://en.wikipedia.org/wiki/Token_bucket +[52]: #inflightrequestthrottle -[53]: http://tools.ietf.org/html/draft-nottingham-http-new-status-03#section-4 +[53]: #parameters-14 -[54]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error +[54]: #examples-14 -[55]: #starthandlertimerhandlername +[55]: #cpuusagethrottle -[56]: #endhandlertimerhandlername +[56]: #parameters-15 -[57]: https://developer.mozilla.org/Add-ons/SDK/High-Level_APIs/request +[57]: #examples-15 -[58]: https://developer.mozilla.org/docs/Web/Guide/HTML/HTML5 +[58]: #conditionalhandler -[59]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined +[59]: #parameters-16 + +[60]: #examples-16 + +[61]: #conditionalrequest + +[62]: #examples-17 + +[63]: #auditlogger + +[64]: #parameters-17 + +[65]: #examples-18 + +[66]: #metrics + +[67]: #parameters-18 + +[68]: #examples-19 + +[69]: #types + +[70]: #metricscallback + +[71]: #parameters-19 + +[72]: #reqset + +[73]: #parameters-20 + +[74]: #reqget + +[75]: #parameters-21 + +[76]: #reqgetall + +[77]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function + +[78]: https://github.com/restify/node-restify/issues/287 + +[79]: https://github.com/restify/node-restify/issues/409 + +[80]: https://github.com/restify/node-restify/wiki/1.4-to-2.0-Migration-Tips + +[81]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object + +[82]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array + +[83]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String + +[84]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp + +[85]: https://github.com/joyent/node-http-signature + +[86]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number + +[87]: https://github.com/ljharb/qs + +[88]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean + +[89]: https://github.com/felixge/node-formidable + +[90]: https://github.com/pinojs/pino + +[91]: #request-api + +[92]: https://github.com/restify/node-restify/issues/284 + +[93]: https://github.com/pillarjs/send + +[94]: http://en.wikipedia.org/wiki/Token_bucket + +[95]: http://tools.ietf.org/html/draft-nottingham-http-new-status-03#section-4 + +[96]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error + +[97]: #starthandlertimerhandlername + +[98]: #endhandlertimerhandlername + +[99]: https://developer.mozilla.org/Add-ons/SDK/High-Level_APIs/request + +[100]: https://developer.mozilla.org/docs/Web/Guide/HTML/HTML5 + +[101]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined diff --git a/docs/_api/request.md b/docs/_api/request.md index b4e909031..a685d2d96 100644 --- a/docs/_api/request.md +++ b/docs/_api/request.md @@ -9,39 +9,55 @@ permalink: /docs/request-api/ - [Request][1] - [accepts][2] - - [acceptsEncoding][3] - - [contentLength][4] - - [getContentType][5] - - [date][6] - - [href][7] - - [id][8] - - [getPath][9] - - [getQuery][10] - - [time][11] - - [version][12] - - [header][13] - - [trailer][14] - - [is][15] - - [isChunked][16] - - [isKeepAlive][17] - - [isSecure][18] - - [isUpgradeRequest][19] - - [isUpload][20] - - [toString][21] - - [userAgent][22] - - [startHandlerTimer][23] - - [endHandlerTimer][24] - - [connectionState][25] - - [getRoute][26] -- [Events][27] -- [Log][28] + - [Parameters][3] + - [Examples][4] + - [acceptsEncoding][5] + - [Parameters][6] + - [contentLength][7] + - [getContentType][8] + - [date][9] + - [href][10] + - [Examples][11] + - [id][12] + - [Parameters][13] + - [getPath][14] + - [Examples][15] + - [getQuery][16] + - [Examples][17] + - [time][18] + - [version][19] + - [header][20] + - [Parameters][21] + - [Examples][22] + - [trailer][23] + - [Parameters][24] + - [is][25] + - [Parameters][26] + - [Examples][27] + - [isChunked][28] + - [isKeepAlive][29] + - [isSecure][30] + - [isUpgradeRequest][31] + - [isUpload][32] + - [toString][33] + - [userAgent][34] + - [startHandlerTimer][35] + - [Parameters][36] + - [Examples][37] + - [endHandlerTimer][38] + - [Parameters][39] + - [connectionState][40] + - [getRoute][41] + - [Examples][42] +- [Events][43] +- [Log][44] ## Request **Extends http.IncomingMessage** Wraps all of the node -[http.IncomingMessage][29] +[http.IncomingMessage][45] APIs, events and properties, plus the following. ### accepts @@ -50,11 +66,11 @@ Check if the Accept header is present, and includes the given type. When the Accept header is not present true is returned. Otherwise the given type is matched by an exact match, and then subtypes. -**Parameters** +#### Parameters -- `types` **([String][30] \| [Array][31]<[String][30]>)** an array of accept type headers +- `types` **([String][46] \| [Array][47]<[String][46]>)** an array of accept type headers -**Examples** +#### Examples You may pass the subtype such as html which is then converted internally to text/html using the mime lookup table: @@ -77,43 +93,43 @@ req.accepts('png'); // => false ``` -Returns **[Boolean][32]** is accepteed +Returns **[Boolean][48]** is accepteed ### acceptsEncoding Checks if the request accepts the encoding type(s) specified. -**Parameters** +#### Parameters -- `types` **([String][30] \| [Array][31]<[String][30]>)** an array of accept type headers +- `types` **([String][46] \| [Array][47]<[String][46]>)** an array of accept type headers -Returns **[Boolean][32]** is accepted encoding +Returns **[Boolean][48]** is accepted encoding ### contentLength Returns the value of the content-length header. -Returns **[Number][33]** +Returns **[Number][49]** ### getContentType Returns the value of the content-type header. If a content-type is not set, this will return a default value of `application/octet-stream` -Returns **[String][30]** content type +Returns **[String][46]** content type ### date Returns a Date object representing when the request was setup. Like `time()`, but returns a Date object. -Returns **[Date][34]** date when request began being processed +Returns **[Date][50]** date when request began being processed ### href Returns the full requested URL. -**Examples** +#### Examples ```javascript // incoming request is http://localhost:3000/foo/bar?a=1 @@ -123,7 +139,7 @@ server.get('/:x/bar', function(req, res, next) { }); ``` -Returns **[String][30]** +Returns **[String][46]** ### id @@ -132,17 +148,17 @@ this will become the request’s new id. The request id is immutable, and can only be set once. Attempting to set the request id more than once will cause restify to throw. -**Parameters** +#### Parameters -- `reqId` **[String][30]** request id +- `reqId` **[String][46]** request id -Returns **[String][30]** id +Returns **[String][46]** id ### getPath Returns the cleaned up requested URL. -**Examples** +#### Examples ```javascript // incoming request is http://localhost:3000/foo/bar?a=1 @@ -152,14 +168,14 @@ server.get('/:x/bar', function(req, res, next) { }); ``` -Returns **[String][30]** +Returns **[String][46]** ### getQuery Returns the raw query string. Returns empty string if no query string is found. -**Examples** +#### Examples ```javascript // incoming request is /foo?a=1 @@ -178,14 +194,14 @@ req.query; // => { a: 1 } ``` -Returns **[String][30]** query +Returns **[String][46]** query ### time The number of ms since epoch of when this request began being processed. Like date(), but returns a number. -Returns **[Number][33]** time when request began being processed in epoch: +Returns **[Number][49]** time when request began being processed in epoch: ellapsed milliseconds since January 1, 1970, 00:00:00 UTC @@ -193,7 +209,7 @@ Returns **[Number][33]** time when request began being processed in epoch: Returns the accept-version header. -Returns **[String][30]** +Returns **[String][46]** ### header @@ -202,13 +218,13 @@ and optionally provide a default value (express-compliant). Returns any header off the request. also, 'correct' any correctly spelled 'referrer' header to the actual spelling used. -**Parameters** +#### Parameters -- `key` **[String][30]** the key of the header -- `defaultValue` **[String][30]?** default value if header isn't +- `key` **[String][46]** the key of the header +- `defaultValue` **[String][46]?** default value if header isn't found on the req -**Examples** +#### Examples ```javascript req.header('Host'); @@ -216,30 +232,30 @@ req.header('HOST'); req.header('Accept', '*\/*'); ``` -Returns **[String][30]** header value +Returns **[String][46]** header value ### trailer Returns any trailer header off the request. Also, 'correct' any correctly spelled 'referrer' header to the actual spelling used. -**Parameters** +#### Parameters -- `name` **[String][30]** the name of the header -- `value` **[String][30]** default value if header isn't found on the req +- `name` **[String][46]** the name of the header +- `value` **[String][46]** default value if header isn't found on the req -Returns **[String][30]** trailer value +Returns **[String][46]** trailer value ### is Check if the incoming request contains the `Content-Type` header field, and if it contains the given mime type. -**Parameters** +#### Parameters -- `type` **[String][30]** a content-type header value +- `type` **[String][46]** a content-type header value -**Examples** +#### Examples ```javascript // With Content-Type: text/html; charset=utf-8 @@ -256,49 +272,49 @@ req.is('html'); // => false ``` -Returns **[Boolean][32]** is content-type header +Returns **[Boolean][48]** is content-type header ### isChunked Check if the incoming request is chunked. -Returns **[Boolean][32]** is chunked +Returns **[Boolean][48]** is chunked ### isKeepAlive Check if the incoming request is kept alive. -Returns **[Boolean][32]** is keep alive +Returns **[Boolean][48]** is keep alive ### isSecure Check if the incoming request is encrypted. -Returns **[Boolean][32]** is secure +Returns **[Boolean][48]** is secure ### isUpgradeRequest Check if the incoming request has been upgraded. -Returns **[Boolean][32]** is upgraded +Returns **[Boolean][48]** is upgraded ### isUpload Check if the incoming request is an upload verb. -Returns **[Boolean][32]** is upload +Returns **[Boolean][48]** is upload ### toString toString serialization -Returns **[String][30]** serialized request +Returns **[String][46]** serialized request ### userAgent Returns the user-agent header. -Returns **[String][30]** user agent +Returns **[String][46]** user agent ### startHandlerTimer @@ -308,11 +324,11 @@ registered in your handler chain. However, this can be called manually for nested functions inside the handler chain to record timing information. -**Parameters** +#### Parameters -- `handlerName` **[String][30]** The name of the handler. +- `handlerName` **[String][46]** The name of the handler. -**Examples** +#### Examples You must explicitly invoke endHandlerTimer() after invoking this function. Otherwise timing @@ -341,7 +357,7 @@ server.get('/', function fooHandler(req, res, next) { }); ``` -Returns **[undefined][35]** no return value +Returns **[undefined][51]** no return value ### endHandlerTimer @@ -349,11 +365,11 @@ End the timer for a request handler. You must invoke this function if you called `startRequestHandler` on a handler. Otherwise the time recorded will be incorrect. -**Parameters** +#### Parameters -- `handlerName` **[String][30]** The name of the handler. +- `handlerName` **[String][46]** The name of the handler. -Returns **[undefined][35]** no return value +Returns **[undefined][51]** no return value ### connectionState @@ -361,13 +377,13 @@ Returns the connection state of the request. Current possible values are: - `close` - when the request has been closed by the clien -Returns **[String][30]** connection state (`"close"`) +Returns **[String][46]** connection state (`"close"`) ### getRoute Returns the route object to which the current request was matched to. -**Examples** +#### Examples Route info object structure: @@ -381,12 +397,12 @@ Route info object structure: } ``` -Returns **[Object][36]** route +Returns **[Object][52]** route ## Events In additional to emitting all the events from node's -[http.Server][37], +[http.Server][53], restify servers also emit a number of additional events that make building REST and web applications much easier. @@ -479,7 +495,7 @@ routable, i.e. one that would result in a `404`. ### uncaughtException If the restify server was created with `handleUncaughtExceptions: true`, -restify will leverage [domains][38] to handle +restify will leverage [domains][54] to handle thrown errors in the handler chain. Thrown errors are a result of an explicit `throw` statement, or as a result of programmer errors like a typo or a null ref. These thrown errors are caught by the domain, and will be emitted via this @@ -491,15 +507,21 @@ server.get('/', function(req, res, next) { return next(); }); -server.on('uncaughtException', function(req, res, route, err) { +server.on('uncaughtException', function(req, res, route, err, callback) { // this event will be fired, with the error object from above: // ReferenceError: x is not defined + res.send(504, 'boom'); + callback(); }); ``` -If you listen to this event, you **must** send a response to the client. This -behavior is different from the standard error events. If you do not listen to -this event, restify's default behavior is to call `res.send()` with the error +If you listen to this event, you **must**: + +1. send a response to the client _and_ +2. call the callback function passed as the fourth argument of the event listener + +This behavior is different from the standard error events. If you do not listen +to this event, restify's default behavior is to call `res.send()` with the error that was thrown. The signature is for the after event is as follows: @@ -520,7 +542,7 @@ Emitted when the server closes. ## Log -If you are using the [RequestLogger][39] plugin, the child logger +If you are using the [RequestLogger][55] plugin, the child logger will be available on `req.log`: ```js @@ -541,76 +563,108 @@ separate handlers. [2]: #accepts -[3]: #acceptsencoding +[3]: #parameters + +[4]: #examples + +[5]: #acceptsencoding + +[6]: #parameters-1 + +[7]: #contentlength + +[8]: #getcontenttype + +[9]: #date + +[10]: #href + +[11]: #examples-1 + +[12]: #id + +[13]: #parameters-2 + +[14]: #getpath + +[15]: #examples-2 + +[16]: #getquery + +[17]: #examples-3 + +[18]: #time + +[19]: #version -[4]: #contentlength +[20]: #header -[5]: #getcontenttype +[21]: #parameters-3 -[6]: #date +[22]: #examples-4 -[7]: #href +[23]: #trailer -[8]: #id +[24]: #parameters-4 -[9]: #getpath +[25]: #is -[10]: #getquery +[26]: #parameters-5 -[11]: #time +[27]: #examples-5 -[12]: #version +[28]: #ischunked -[13]: #header +[29]: #iskeepalive -[14]: #trailer +[30]: #issecure -[15]: #is +[31]: #isupgraderequest -[16]: #ischunked +[32]: #isupload -[17]: #iskeepalive +[33]: #tostring -[18]: #issecure +[34]: #useragent -[19]: #isupgraderequest +[35]: #starthandlertimer -[20]: #isupload +[36]: #parameters-6 -[21]: #tostring +[37]: #examples-6 -[22]: #useragent +[38]: #endhandlertimer -[23]: #starthandlertimer +[39]: #parameters-7 -[24]: #endhandlertimer +[40]: #connectionstate -[25]: #connectionstate +[41]: #getroute -[26]: #getroute +[42]: #examples-7 -[27]: #events +[43]: #events -[28]: #log +[44]: #log -[29]: https://nodejs.org/api/http.html +[45]: https://nodejs.org/api/http.html -[30]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[46]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String -[31]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[47]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array -[32]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[48]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean -[33]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number +[49]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number -[34]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date +[50]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date -[35]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined +[51]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined -[36]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[52]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object -[37]: http://nodejs.org/docs/latest/api/http.html#http_class_http_server +[53]: http://nodejs.org/docs/latest/api/http.html#http_class_http_server -[38]: https://nodejs.org/api/domain.html +[54]: https://nodejs.org/api/domain.html -[39]: #bundled-plugins +[55]: #bundled-plugins diff --git a/docs/_api/response.md b/docs/_api/response.md index e47388d16..4478ae139 100644 --- a/docs/_api/response.md +++ b/docs/_api/response.md @@ -9,72 +9,93 @@ permalink: /docs/response-api/ - [Response][1] - [cache][2] - - [noCache][3] - - [charSet][4] - - [header][5] - - [json][6] - - [link][7] - - [send][8] - - [sendRaw][9] - - [set][10] - - [status][11] - - [redirect][12] - - [redirect][13] - - [redirect][14] + - [Parameters][3] + - [noCache][4] + - [charSet][5] + - [Parameters][6] + - [Examples][7] + - [header][8] + - [Parameters][9] + - [Examples][10] + - [json][11] + - [Parameters][12] + - [Examples][13] + - [link][14] + - [Parameters][15] + - [send][16] + - [Parameters][17] + - [Examples][18] + - [sendRaw][19] + - [Parameters][20] + - [set][21] + - [Parameters][22] + - [Examples][23] + - [status][24] + - [Parameters][25] + - [Examples][26] + - [redirect][27] + - [Parameters][28] + - [Examples][29] + - [redirect][30] + - [Parameters][31] + - [Examples][32] + - [redirect][33] + - [Parameters][34] + - [Examples][35] ## Response **Extends http.ServerResponse** Wraps all of the node -[http.ServerResponse][15] +[http.ServerResponse][36] APIs, events and properties, plus the following. ### cache Sets the `cache-control` header. -**Parameters** +#### Parameters -- `type` **[String][16]** value of the header +- `type` **[String][37]** value of the header (`"public"` or `"private"`) (optional, default `"public"`) -- `options` **[Object][17]?** an options object - - `options.maxAge` **[Number][18]** max-age in seconds +- `options` **[Object][38]?** an options object + - `options.maxAge` **[Number][39]** max-age in seconds -Returns **[String][16]** the value set to the header +Returns **[String][37]** the value set to the header ### noCache Turns off all cache related headers. -Returns **[Response][19]** self, the response object +Returns **[Response][40]** self, the response object ### charSet Appends the provided character set to the response's `Content-Type`. -**Parameters** +#### Parameters -- `type` **[String][16]** char-set value +- `type` **[String][37]** char-set value -**Examples** +#### Examples ```javascript res.charSet('utf-8'); ``` -Returns **[Response][19]** self, the response object +Returns **[Response][40]** self, the response object ### header Sets headers on the response. -**Parameters** +#### Parameters -- `key` **[String][16]** the name of the header -- `value` **[String][16]** the value of the header +- `key` **[String][37]** the name of the header +- `value` **[String][37]** the value of the header -**Examples** +#### Examples If only key is specified, return the value of the header. If both key and value are specified, set the response header. @@ -104,7 +125,7 @@ res.header('x-foo', 'b'); // => { 'x-foo': ['a', 'b'] } ``` -Returns **[Object][17]** the retrieved value or the value that was set +Returns **[Object][38]** the retrieved value or the value that was set ### json @@ -115,44 +136,44 @@ res.contentType = 'json'; res.send({hello: 'world'}); ``` -**Parameters** +#### Parameters -- `code` **[Number][18]?** http status code -- `body` **[Object][17]?** value to json.stringify -- `headers` **[Object][17]?** headers to set on the response +- `code` **[Number][39]?** http status code +- `body` **[Object][38]?** value to json.stringify +- `headers` **[Object][38]?** headers to set on the response -**Examples** +#### Examples ```javascript res.header('content-type', 'json'); res.send({hello: 'world'}); ``` -Returns **[Object][17]** the response object +Returns **[Object][38]** the response object ### link Sets the link header. -**Parameters** +#### Parameters -- `key` **[String][16]** the link key -- `value` **[String][16]** the link value +- `key` **[String][37]** the link key +- `value` **[String][37]** the link value -Returns **[String][16]** the header value set to res +Returns **[String][37]** the header value set to res ### send Sends the response object. pass through to internal `__send` that uses a formatter based on the `content-type` header. -**Parameters** +#### Parameters -- `code` **[Number][18]?** http status code -- `body` **([Object][17] \| [Buffer][20] \| [Error][21])?** the content to send -- `headers` **[Object][17]?** any add'l headers to set +- `code` **[Number][39]?** http status code +- `body` **([Object][38] \| [Buffer][41] \| [Error][42])?** the content to send +- `headers` **[Object][38]?** any add'l headers to set -**Examples** +#### Examples You can use send() to wrap up all the usual writeHead(), write(), end() calls on the HTTP API of node. @@ -168,7 +189,7 @@ res.send(201, {hello: 'world'}); res.send(new BadRequestError('meh')); ``` -Returns **[Object][17]** the response object +Returns **[Object][38]** the response object ### sendRaw @@ -177,26 +198,26 @@ payload has already been preformatted. Sends the response object. pass through to internal `__send` that skips formatters entirely and sends the content as is. -**Parameters** +#### Parameters -- `code` **[Number][18]?** http status code -- `body` **([Object][17] \| [Buffer][20] \| [Error][21])?** the content to send -- `headers` **[Object][17]?** any add'l headers to set +- `code` **[Number][39]?** http status code +- `body` **([string][37] \| [Buffer][41])?** the content to send +- `headers` **[Object][38]?** any add'l headers to set -Returns **[Object][17]** the response object +Returns **[Object][38]** the response object ### set Sets multiple header(s) on the response. Uses `header()` underneath the hood, enabling multi-value headers. -**Parameters** +#### Parameters -- `name` **([String][16] \| [Object][17])** name of the header or +- `name` **([String][37] \| [Object][38])** name of the header or `Object` of headers -- `val` **[String][16]** value of the header +- `val` **[String][37]** value of the header -**Examples** +#### Examples ```javascript res.header('x-foo', 'a'); @@ -211,46 +232,46 @@ res.set({ // } ``` -Returns **[Object][17]** self, the response object +Returns **[Object][38]** self, the response object ### status Sets the http status code on the response. -**Parameters** +#### Parameters -- `code` **[Number][18]** http status code +- `code` **[Number][39]** http status code -**Examples** +#### Examples ```javascript res.status(201); ``` -Returns **[Number][18]** the status code passed in +Returns **[Number][39]** the status code passed in ### redirect Redirect is sugar method for redirecting. -**Parameters** +#### Parameters -- `options` **[Object][17]** url or an options object to configure a redirect - - `options.secure` **[Boolean][22]?** whether to redirect to http or https - - `options.hostname` **[String][16]?** redirect location's hostname - - `options.pathname` **[String][16]?** redirect location's pathname - - `options.port` **[String][16]?** redirect location's port number - - `options.query` **[String][16]?** redirect location's query string +- `options` **[Object][38]** url or an options object to configure a redirect + - `options.secure` **[Boolean][43]?** whether to redirect to http or https + - `options.hostname` **[String][37]?** redirect location's hostname + - `options.pathname` **[String][37]?** redirect location's pathname + - `options.port` **[String][37]?** redirect location's port number + - `options.query` **[String][37]?** redirect location's query string parameters - - `options.overrideQuery` **[Boolean][22]?** if true, `options.query` + - `options.overrideQuery` **[Boolean][43]?** if true, `options.query` stomps over any existing query parameters on current URL. by default, will merge the two. - - `options.permanent` **[Boolean][22]?** if true, sets 301. defaults to 302. -- `next` **[Function][23]** mandatory, to complete the response and trigger + - `options.permanent` **[Boolean][43]?** if true, sets 301. defaults to 302. +- `next` **[Function][44]** mandatory, to complete the response and trigger audit logger. -**Examples** +#### Examples ```javascript res.redirect({...}, next); @@ -274,90 +295,132 @@ res.redirect({ }, next); // => redirects to 301 https://www.foo.com/bar?a=1 ``` -Returns **[undefined][24]** +Returns **[undefined][45]** ### redirect Redirect with code and url. -**Parameters** +#### Parameters -- `code` **[Number][18]** http redirect status code -- `url` **[String][16]** redirect url -- `next` **[Function][23]** mandatory, to complete the response and trigger +- `code` **[Number][39]** http redirect status code +- `url` **[String][37]** redirect url +- `next` **[Function][44]** mandatory, to complete the response and trigger audit logger. -**Examples** +#### Examples ```javascript res.redirect(301, 'www.foo.com', next); ``` -Returns **[undefined][24]** +Returns **[undefined][45]** ### redirect Redirect with url. -**Parameters** +#### Parameters -- `url` **[String][16]** redirect url -- `next` **[Function][23]** mandatory, to complete the response and trigger +- `url` **[String][37]** redirect url +- `next` **[Function][44]** mandatory, to complete the response and trigger audit logger. -**Examples** +#### Examples ```javascript res.redirect('www.foo.com', next); res.redirect('/foo', next); ``` -Returns **[undefined][24]** +Returns **[undefined][45]** [1]: #response [2]: #cache -[3]: #nocache +[3]: #parameters -[4]: #charset +[4]: #nocache -[5]: #header +[5]: #charset -[6]: #json +[6]: #parameters-1 -[7]: #link +[7]: #examples -[8]: #send +[8]: #header -[9]: #sendraw +[9]: #parameters-2 -[10]: #set +[10]: #examples-1 -[11]: #status +[11]: #json -[12]: #redirect +[12]: #parameters-3 -[13]: #redirect-1 +[13]: #examples-2 -[14]: #redirect-2 +[14]: #link -[15]: https://nodejs.org/docs/latest/api/http.html +[15]: #parameters-4 -[16]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[16]: #send -[17]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[17]: #parameters-5 -[18]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number +[18]: #examples-3 -[19]: #response +[19]: #sendraw -[20]: https://nodejs.org/api/buffer.html +[20]: #parameters-6 -[21]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error +[21]: #set -[22]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[22]: #parameters-7 -[23]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function +[23]: #examples-4 -[24]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined +[24]: #status + +[25]: #parameters-8 + +[26]: #examples-5 + +[27]: #redirect + +[28]: #parameters-9 + +[29]: #examples-6 + +[30]: #redirect-1 + +[31]: #parameters-10 + +[32]: #examples-7 + +[33]: #redirect-2 + +[34]: #parameters-11 + +[35]: #examples-8 + +[36]: https://nodejs.org/docs/latest/api/http.html + +[37]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String + +[38]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object + +[39]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number + +[40]: #response + +[41]: https://nodejs.org/api/buffer.html + +[42]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error + +[43]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean + +[44]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function + +[45]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined diff --git a/docs/_api/server.md b/docs/_api/server.md index d497bf19b..0367fe1ae 100644 --- a/docs/_api/server.md +++ b/docs/_api/server.md @@ -8,80 +8,112 @@ permalink: /docs/server-api/ ### Table of Contents - [createServer][1] -- [Server][2] - - [listen][3] - - [close][4] - - [get][5] - - [head][6] - - [post][7] - - [put][8] - - [patch][9] - - [del][10] - - [opts][11] - - [pre][12] - - [use][13] - - [param][14] - - [rm][15] - - [address][16] - - [inflightRequests][17] - - [debugInfo][18] - - [toString][19] -- [Events][20] -- [Errors][21] -- [Types][22] - - [Server~methodOpts][23] + - [Parameters][2] + - [Examples][3] +- [Server][4] + - [Parameters][5] + - [Examples][6] + - [listen][7] + - [Parameters][8] + - [Examples][9] + - [close][10] + - [Parameters][11] + - [get][12] + - [Parameters][13] + - [Examples][14] + - [head][15] + - [Parameters][16] + - [post][17] + - [Parameters][18] + - [put][19] + - [Parameters][20] + - [patch][21] + - [Parameters][22] + - [del][23] + - [Parameters][24] + - [opts][25] + - [Parameters][26] + - [pre][27] + - [Parameters][28] + - [Examples][29] + - [first][30] + - [Parameters][31] + - [Examples][32] + - [use][33] + - [Parameters][34] + - [Examples][35] + - [param][36] + - [Parameters][37] + - [Examples][38] + - [rm][39] + - [Parameters][40] + - [address][41] + - [Examples][42] + - [inflightRequests][43] + - [debugInfo][44] + - [Examples][45] + - [toString][46] + - [Examples][47] +- [Events][48] +- [Errors][49] +- [Types][50] + - [Server~methodOpts][51] + - [Properties][52] + - [Examples][53] +- [proxyEventWhenListenerAdded][54] + - [Parameters][55] ## createServer A restify server object is the main interface through which you will register routes and handlers for incoming requests. -**Parameters** +### Parameters -- `options` **[Object][24]?** an options object - - `options.name` **[String][25]** Name of the server. (optional, default `"restify"`) - - `options.dtrace` **[Boolean][26]** enable DTrace support (optional, default `false`) +- `options` **[Object][56]?** an options object + - `options.name` **[String][57]** Name of the server. (optional, default `"restify"`) + - `options.dtrace` **[Boolean][58]** enable DTrace support (optional, default `false`) - `options.router` **Router** Router (optional, default `newRouter(opts)`) - - `options.log` **[Object][24]** [bunyan][27] instance. (optional, default `bunyan.createLogger(options.name||"restify")`) - - `options.url` **[String][25]?** Once listen() is called, this will be filled + - `options.log` **[Object][56]** [pino][59] instance. (optional, default `pino({name:options.name||"restify"})`) + - `options.url` **[String][57]?** Once listen() is called, this will be filled in with where the server is running. - - `options.certificate` **([String][25] \| [Buffer][28])?** If you want to create an HTTPS + - `options.certificate` **([String][57] \| [Buffer][60])?** If you want to create an HTTPS server, pass in a PEM-encoded certificate and key. - - `options.key` **([String][25] \| [Buffer][28])?** If you want to create an HTTPS server, + - `options.key` **([String][57] \| [Buffer][60])?** If you want to create an HTTPS server, pass in a PEM-encoded certificate and key. - - `options.formatters` **[Object][24]?** Custom response formatters for + - `options.formatters` **[Object][56]?** Custom response formatters for `res.send()`. - - `options.handleUncaughtExceptions` **[Boolean][26]** When true restify + - `options.handleUncaughtExceptions` **[Boolean][58]** When true restify will use a domain to catch and respond to any uncaught exceptions that occur in its handler stack. Comes with significant negative performance impact. (optional, default `false`) - - `options.spdy` **[Object][24]?** Any options accepted by - [node-spdy][29]. - - `options.http2` **[Object][24]?** Any options accepted by - [http2.createSecureServer][30]. - - `options.handleUpgrades` **[Boolean][26]** Hook the `upgrade` event + - `options.spdy` **[Object][56]?** Any options accepted by + [node-spdy][61]. + - `options.http2` **[Object][56]?** Any options accepted by + [http2.createSecureServer][62]. + - `options.handleUpgrades` **[Boolean][58]** Hook the `upgrade` event from the node HTTP server, pushing `Connection: Upgrade` requests through the regular request handling chain. (optional, default `false`) - - `options.onceNext` **[Boolean][26]** Prevents calling next multiple + - `options.onceNext` **[Boolean][58]** Prevents calling next multiple times (optional, default `false`) - - `options.strictNext` **[Boolean][26]** Throws error when next() is + - `options.strictNext` **[Boolean][58]** Throws error when next() is called more than once, enabled onceNext option (optional, default `false`) - - `options.httpsServerOptions` **[Object][24]?** Any options accepted by - [node-https Server][31]. + - `options.httpsServerOptions` **[Object][56]?** Any options accepted by + [node-https Server][63]. If provided the following restify server options will be ignored: spdy, ca, certificate, key, passphrase, rejectUnauthorized, requestCert and ciphers; however these can all be specified on httpsServerOptions. - - `options.noWriteContinue` **[Boolean][26]** prevents + - `options.noWriteContinue` **[Boolean][58]** prevents `res.writeContinue()` in `server.on('checkContinue')` when proxing (optional, default `false`) - - `options.ignoreTrailingSlash` **[Boolean][26]** ignore trailing slash + - `options.ignoreTrailingSlash` **[Boolean][58]** ignore trailing slash on paths (optional, default `false`) - - `options.strictFormatters` **[Boolean][26]** enables strict formatters + - `options.strictFormatters` **[Boolean][58]** enables strict formatters behavior: a formatter matching the response's content-type is required. If not found, the response's content-type is automatically set to 'application/octet-stream'. If a formatter for that content-type is not found, sending the response errors. (optional, default `true`) -**Examples** +### Examples ```javascript var restify = require('restify'); @@ -92,59 +124,66 @@ server.listen(8080, function () { }); ``` -Returns **[Server][32]** server +Returns **[Server][64]** server ## Server Creates a new Server. -**Parameters** +### Parameters -- `options` **[Object][24]** an options object - - `options.name` **[String][25]** Name of the server. - - `options.dtrace` **[Boolean][26]** enable DTrace support (optional, default `false`) +- `options` **[Object][56]** an options object + - `options.name` **[String][57]** Name of the server. + - `options.dtrace` **[Boolean][58]** enable DTrace support (optional, default `false`) - `options.router` **Router** Router - - `options.log` **[Object][24]** [bunyan][27] + - `options.log` **[Object][56]** [pino][59] instance. - - `options.url` **[String][25]?** Once listen() is called, this will be filled + - `options.url` **[String][57]?** Once listen() is called, this will be filled in with where the server is running. - - `options.certificate` **([String][25] \| [Buffer][28])?** If you want to create an HTTPS + - `options.certificate` **([String][57] \| [Buffer][60])?** If you want to create an HTTPS server, pass in a PEM-encoded certificate and key. - - `options.key` **([String][25] \| [Buffer][28])?** If you want to create an HTTPS server, + - `options.key` **([String][57] \| [Buffer][60])?** If you want to create an HTTPS server, pass in a PEM-encoded certificate and key. - - `options.formatters` **[Object][24]?** Custom response formatters for + - `options.formatters` **[Object][56]?** Custom response formatters for `res.send()`. - - `options.handleUncaughtExceptions` **[Boolean][26]** When true restify - will use a domain to catch and respond to any uncaught - exceptions that occur in its handler stack. - Comes with significant negative performance impact. - - `options.spdy` **[Object][24]?** Any options accepted by - [node-spdy][29]. - - `options.http2` **[Object][24]?** Any options accepted by - [http2.createSecureServer][30]. - - `options.handleUpgrades` **[Boolean][26]** Hook the `upgrade` event + - `options.handleUncaughtExceptions` **([Boolean][58] \| [Function][65])** When + true restify will use a domain to catch and respond to any uncaught + exceptions that occur in its handler stack. Comes with significant negative + performance impact. + Can also receive a function with signature (req, res, onError, next), + allowing for domains alternatives. onError should be called by the custom + error handler, and next must be called at the end of this function. THIS + FUNCTION IS NOT INTENDED TO BE USED TO HANDLE ERRORS DIRECTLY, IT IS ONLY + INTENDED AS AN ALTERNATIVE TO `domains`. + onError signature: (err, req, res) + next signature: (res, res) (optional, default `false`) + - `options.spdy` **[Object][56]?** Any options accepted by + [node-spdy][61]. + - `options.http2` **[Object][56]?** Any options accepted by + [http2.createSecureServer][62]. + - `options.handleUpgrades` **[Boolean][58]** Hook the `upgrade` event from the node HTTP server, pushing `Connection: Upgrade` requests through the regular request handling chain. (optional, default `false`) - - `options.onceNext` **[Boolean][26]** Prevents calling next multiple + - `options.onceNext` **[Boolean][58]** Prevents calling next multiple times (optional, default `false`) - - `options.strictNext` **[Boolean][26]** Throws error when next() is + - `options.strictNext` **[Boolean][58]** Throws error when next() is called more than once, enabled onceNext option (optional, default `false`) - - `options.httpsServerOptions` **[Object][24]?** Any options accepted by - [node-https Server][31]. + - `options.httpsServerOptions` **[Object][56]?** Any options accepted by + [node-https Server][63]. If provided the following restify server options will be ignored: spdy, ca, certificate, key, passphrase, rejectUnauthorized, requestCert and ciphers; however these can all be specified on httpsServerOptions. - - `options.noWriteContinue` **[Boolean][26]** prevents + - `options.noWriteContinue` **[Boolean][58]** prevents `res.writeContinue()` in `server.on('checkContinue')` when proxing (optional, default `false`) - - `options.ignoreTrailingSlash` **[Boolean][26]** ignore trailing slash + - `options.ignoreTrailingSlash` **[Boolean][58]** ignore trailing slash on paths (optional, default `false`) - - `options.strictFormatters` **[Boolean][26]** enables strict formatters + - `options.strictFormatters` **[Boolean][58]** enables strict formatters behavior: a formatter matching the response's content-type is required. If not found, the response's content-type is automatically set to 'application/octet-stream'. If a formatter for that content-type is not found, sending the response errors. (optional, default `true`) -**Examples** +### Examples ```javascript var restify = require('restify'); @@ -159,15 +198,15 @@ server.listen(8080, function () { Gets the server up and listening. Wraps node's -[listen()][33]. +[listen()][66]. -**Parameters** +#### Parameters -- `port` **[Number][34]** Port -- `host` **[Number][34]?** Host -- `callback` **[Function][35]?** optionally get notified when listening. +- `port` **[Number][67]** Port +- `host` **[Number][67]?** Host +- `callback` **[Function][65]?** optionally get notified when listening. -**Examples** +#### Examples You can call like: @@ -178,32 +217,32 @@ server.listen(80, '127.0.0.1') server.listen('/tmp/server.sock') ``` -- Throws **[TypeError][36]** +- Throws **[TypeError][68]** -Returns **[undefined][37]** no return value +Returns **[undefined][69]** no return value ### close Shuts down this server, and invokes callback (optionally) when done. Wraps node's -[close()][38]. +[close()][70]. -**Parameters** +#### Parameters -- `callback` **[Function][35]?** callback to invoke when done +- `callback` **[Function][65]?** callback to invoke when done -Returns **[undefined][37]** no return value +Returns **[undefined][69]** no return value ### get Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `opts` **[Server~methodOpts][39]** if string, the URL to handle. +- `opts` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. -**Examples** +#### Examples ```javascript server.get('/', function (req, res, next) { @@ -212,15 +251,26 @@ server.get('/', function (req, res, next) { }); ``` +using with async/await + + +```javascript +server.get('/', function (req, res) { + await somethingAsync(); + res.send({ hello: 'world' }); + next(); +} +``` + Returns **Route** the newly created route. ### head Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `opts` **[Server~methodOpts][39]** if string, the URL to handle. +- `opts` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. Returns **Route** the newly created route. @@ -229,9 +279,9 @@ Returns **Route** the newly created route. Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `post` **[Server~methodOpts][39]** if string, the URL to handle. +- `post` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. Returns **Route** the newly created route. @@ -240,9 +290,9 @@ Returns **Route** the newly created route. Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `put` **[Server~methodOpts][39]** if string, the URL to handle. +- `put` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. Returns **Route** the newly created route. @@ -251,9 +301,9 @@ Returns **Route** the newly created route. Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `patch` **[Server~methodOpts][39]** if string, the URL to handle. +- `patch` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. Returns **Route** the newly created route. @@ -262,9 +312,9 @@ Returns **Route** the newly created route. Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `opts` **[Server~methodOpts][39]** if string, the URL to handle. +- `opts` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. Returns **Route** the newly created route. @@ -273,22 +323,24 @@ Returns **Route** the newly created route. Mounts a chain on the given path against this HTTP verb -**Parameters** +#### Parameters -- `opts` **[Server~methodOpts][39]** if string, the URL to handle. +- `opts` **[Server~methodOpts][71]** if string, the URL to handle. if options, the URL to handle, at minimum. Returns **Route** the newly created route. ### pre +- **See: [Restify pre() plugins][72]** + Gives you hooks to run _before_ any routes are located. This gives you a chance to intercept the request and change headers, etc., that routing depends on. Note that req.params will _not_ be set yet. -**Parameters** +#### Parameters -- `handler` **...([Function][35] \| [Array][40])** Allows you to add handlers that +- `handler` **...([Function][65] \| [Array][73])** Allows you to add handlers that run for all routes. _before_ routing occurs. This gives you a hook to change request headers and the like if you need to. Note that `req.params` will be undefined, as that's filled in _after_ @@ -296,7 +348,7 @@ depends on. Note that req.params will _not_ be set yet. Takes a function, or an array of functions. variable number of nested arrays of handler functions -**Examples** +#### Examples ```javascript server.pre(function(req, res, next) { @@ -305,6 +357,16 @@ server.pre(function(req, res, next) { }); ``` +using with async/await + + +```javascript +server.pre(async function(req, res) { + await somethingAsync(); + somethingSync(); +} +``` + For example, `pre()` can be used to deduplicate slashes in URLs @@ -313,10 +375,72 @@ URLs server.pre(restify.pre.dedupeSlashes()); ``` -Returns **[Object][24]** returns self +Returns **[Object][56]** returns self + +### first + +Gives you hooks that run before restify touches a request. These hooks +allow you to do processing early in the request/response life cycle without +the overhead of the restify framework. You can not yield the event loop in +this handler. + +The function handler accepts two parameters: req, res. If you want restify +to ignore this request, return false from your handler. Return true or +undefined to let restify continue handling the request. + +When false is returned, restify immediately stops handling the request. This +means that no further middleware will be executed for any chain and routing +will not occure. All request/response handling for an incoming request must +be done inside the first handler if you intend to return false. This +includes things like closing the response and returning a status code. + +The only work restify does for a first handler is to increment the number of +inflightRequests prior to calling the chain, and decrement that value if the +handler returns false. Returning anything other than true, false, undefined, +or null will cause an exception to be thrown. + +Since server.first is designed to bypass the restify framework, there are +naturally trade-offs you make when using this API: + +- Standard restify lifecycle events such as 'after' are not triggered for + any request that you return false from a handler for +- Invoking any of the restify req/res APIs from within a first handler is + unspecified behavior, as the restify framework hasn't built up state for + the request yet. +- There are no request timers available at the time that the first chain + runs. +- And more! Beware doing anything with restify in these handlers. They are + designed to give you similar access to the req/res as you would have if + you were directly using node.js' http module, they are outside of the + restify framework! + +#### Parameters + +- `handler` **...[Function][65]** Allows you to add handlers that + run for all requests, _before_ restify touches the request. + This gives you a hook to change request headers and the like if you need to. + Note that `req.params` will be undefined, as that's filled in _after_ + routing.Takes one or more functions. + +#### Examples + +```javascript +server.first(function(req, res) { + if(server.inflightRequests() > 100) { + res.statusCode = 503; + res.end(); + return false + } + return true; +}) +``` + +Returns **[Object][56]** returns self ### use +- **See: [Restify use() plugins][74]** + Allows you to add in handlers that run for all routes. Note that handlers added via `use()` will run only after the router has found a matching route. If no @@ -325,16 +449,42 @@ of functions. You can pass in any combination of functions or array of functions. -**Parameters** +#### Parameters -- `handler` **...([Function][35] \| [Array][40])** A variable number of handler functions- and/or a +- `handler` **...([Function][65] \| [Array][73])** A variable number of handler functions- and/or a variable number of nested arrays of handler functions -Returns **[Object][24]** returns self +#### Examples + +```javascript +server.use(function(req, res, next) { + // do something... + return next(); +}); +``` + +using with async/await + + +```javascript +server.use(async function(req, res) { + await somethingAsync(); + somethingSync(); +} +``` + +For example, `use()` can be used to attach a request logger + + +```javascript +server.pre(restify.plugins.requestLogger()); +``` + +Returns **[Object][56]** returns self ### param -- **See: [http://expressjs.com/guide.html#route-param%20pre-conditions][41]** +- **See: [ Express route param pre-conditions][75]** Minimal port of the functionality offered by Express.js Route Param Pre-conditions @@ -343,39 +493,56 @@ This basically piggy-backs on the `server.use` method. It attaches a new middleware function that only fires if the specified parameter exists in req.params -Exposes an API: - server.param("user", function (req, res, next) { - // load the user's information here, always making sure to call next() +#### Parameters + +- `name` **[String][57]** The name of the URL param to respond to +- `fn` **[Function][65]** The middleware function to execute + +#### Examples + +```javascript +server.param("user", function (req, res, next) { + // load the user's information here, always making sure to call next() + fetchUserInformation(req, function callback(user) { + req.user = user; + next(); }); +}); +``` + +using with async/await -**Parameters** -- `name` **[String][25]** The name of the URL param to respond to -- `fn` **[Function][35]** The middleware function to execute +```javascript +server.param("user", async function(req, res) { + req.user = await fetchUserInformation(req); + somethingSync(); +} +``` -Returns **[Object][24]** returns self +Returns **[Object][56]** returns self ### rm Removes a route from the server. You pass in the route 'blob' you got from a mount call. -**Parameters** +#### Parameters -- `routeName` **[String][25]** the route name. +- `routeName` **[String][57]** the route name. -- Throws **[TypeError][36]** on bad input. +- Throws **[TypeError][68]** on bad input. -Returns **[Boolean][26]** true if route was removed, false if not. +Returns **[Boolean][58]** true if route was removed, false if not. ### address Returns the server address. Wraps node's -[address()][42]. +[address()][76]. -**Examples** +#### Examples ```javascript server.address() @@ -388,19 +555,19 @@ Output: { address: '::', family: 'IPv6', port: 8080 } ``` -Returns **[Object][24]** Address of server +Returns **[Object][56]** Address of server ### inflightRequests Returns the number of inflight requests currently being handled by the server -Returns **[number][34]** number of inflight requests +Returns **[number][67]** number of inflight requests ### debugInfo Return debug information about the server. -**Examples** +#### Examples ```javascript server.getDebugInfo() @@ -438,13 +605,13 @@ Output: } ``` -Returns **[Object][24]** debug info +Returns **[Object][56]** debug info ### toString toString() the server for easy reading/output. -**Examples** +#### Examples ```javascript server.toString() @@ -474,12 +641,12 @@ Url: http://[::]:8080 Version: ``` -Returns **[String][25]** stringified server +Returns **[String][57]** stringified server ## Events In additional to emitting all the events from node's -[http.Server][43], +[http.Server][77], restify servers also emit a number of additional events that make building REST and web applications much easier. @@ -572,7 +739,7 @@ routable, i.e. one that would result in a `404`. ### uncaughtException If the restify server was created with `handleUncaughtExceptions: true`, -restify will leverage [domains][44] to handle +restify will leverage [domains][78] to handle thrown errors in the handler chain. Thrown errors are a result of an explicit `throw` statement, or as a result of programmer errors like a typo or a null ref. These thrown errors are caught by the domain, and will be emitted via this @@ -584,15 +751,21 @@ server.get('/', function(req, res, next) { return next(); }); -server.on('uncaughtException', function(req, res, route, err) { +server.on('uncaughtException', function(req, res, route, err, callback) { // this event will be fired, with the error object from above: // ReferenceError: x is not defined + res.send(504, 'boom'); + callback(); }); ``` -If you listen to this event, you **must** send a response to the client. This -behavior is different from the standard error events. If you do not listen to -this event, restify's default behavior is to call `res.send()` with the error +If you listen to this event, you **must**: + +1. send a response to the client _and_ +2. call the callback function passed as the fourth argument of the event listener + +This behavior is different from the standard error events. If you do not listen +to this event, restify's default behavior is to call `res.send()` with the error that was thrown. The signature is for the after event is as follows: @@ -679,7 +852,7 @@ function(req, res, err, callback) { } - `callback` - a callback function to invoke When using this feature in conjunction with -[restify-errors][45], restify will emit events +[restify-errors][79], restify will emit events for all of the basic http errors: - `400` - `BadRequestError` @@ -759,15 +932,15 @@ on this event, and if there are none, responds with a default 415 handler. Server method opts -Type: ([String][25] \| [Regexp][46] \| [Object][24]) +Type: [Object][56] -**Properties** +#### Properties -- `name` **[String][25]** a name for the route -- `path` **[String][25]** can be any String accepted by - [find-my-way][47] +- `name` **[String][57]** a name for the route +- `path` **[String][57]** can be any String accepted by + [find-my-way][80] -**Examples** +#### Examples ```javascript // a static route @@ -782,96 +955,176 @@ server.get({ }, function(req, res, next) {}); ``` +## proxyEventWhenListenerAdded + +Only add a listener on the wrappedEmitter when a listener for the event is +added to the wrapperEmitter. This is useful when just adding a listener to +the wrappedEmittter overrides/disables a default behavior. + +### Parameters + +- `eventName` **[string][57]** The name of the event to proxy +- `wrapperEmitter` **EventEmitter** The emitter that proxies events from the wrappedEmitter +- `wrappedEmitter` **EventEmitter** The proxied emitter + +Returns **[undefined][69]** NA + [1]: #createserver -[2]: #server +[2]: #parameters + +[3]: #examples + +[4]: #server + +[5]: #parameters-1 + +[6]: #examples-1 + +[7]: #listen + +[8]: #parameters-2 + +[9]: #examples-2 + +[10]: #close + +[11]: #parameters-3 + +[12]: #get + +[13]: #parameters-4 + +[14]: #examples-3 + +[15]: #head + +[16]: #parameters-5 + +[17]: #post + +[18]: #parameters-6 + +[19]: #put + +[20]: #parameters-7 + +[21]: #patch + +[22]: #parameters-8 + +[23]: #del + +[24]: #parameters-9 + +[25]: #opts + +[26]: #parameters-10 + +[27]: #pre + +[28]: #parameters-11 + +[29]: #examples-4 + +[30]: #first + +[31]: #parameters-12 + +[32]: #examples-5 + +[33]: #use + +[34]: #parameters-13 + +[35]: #examples-6 -[3]: #listen +[36]: #param -[4]: #close +[37]: #parameters-14 -[5]: #get +[38]: #examples-7 -[6]: #head +[39]: #rm -[7]: #post +[40]: #parameters-15 -[8]: #put +[41]: #address -[9]: #patch +[42]: #examples-8 -[10]: #del +[43]: #inflightrequests -[11]: #opts +[44]: #debuginfo -[12]: #pre +[45]: #examples-9 -[13]: #use +[46]: #tostring -[14]: #param +[47]: #examples-10 -[15]: #rm +[48]: #events -[16]: #address +[49]: #errors -[17]: #inflightrequests +[50]: #types -[18]: #debuginfo +[51]: #servermethodopts -[19]: #tostring +[52]: #properties -[20]: #events +[53]: #examples-11 -[21]: #errors +[54]: #proxyeventwhenlisteneradded -[22]: #types +[55]: #parameters-16 -[23]: #servermethodopts +[56]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object -[24]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object +[57]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String -[25]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String +[58]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean -[26]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean +[59]: https://github.com/pinojs/pino -[27]: https://github.com/trentm/node-bunyan +[60]: https://nodejs.org/api/buffer.html -[28]: https://nodejs.org/api/buffer.html +[61]: https://github.com/indutny/node-spdy -[29]: https://github.com/indutny/node-spdy +[62]: https://nodejs.org/api/http2.html -[30]: https://nodejs.org/api/http2.html +[63]: http://nodejs.org/api/https.html#https_https -[31]: http://nodejs.org/api/https.html#https_https +[64]: #server -[32]: #server +[65]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function -[33]: http://nodejs.org/docs/latest/api/net.html#net_server_listen_path_callback +[66]: http://nodejs.org/docs/latest/api/net.html#net_server_listen_path_callback -[34]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number +[67]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number -[35]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function +[68]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypeError -[36]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypeError +[69]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined -[37]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined +[70]: http://nodejs.org/docs/latest/api/net.html#net_event_close -[38]: http://nodejs.org/docs/latest/api/net.html#net_event_close +[71]: #servermethodopts -[39]: #servermethodopts +[72]: http://restify.com/docs/plugins-api/#serverpre-plugins -[40]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array +[73]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array -[41]: http://expressjs.com/guide.html#route-param%20pre-conditions +[74]: http://restify.com/docs/plugins-api/#serveruse-plugins -[42]: http://nodejs.org/docs/latest/api/net.html#net_server_address +[75]: http://expressjs.com/guide.html#route-param%20pre-conditions -[43]: http://nodejs.org/docs/latest/api/http.html#http_class_http_server +[76]: http://nodejs.org/docs/latest/api/net.html#net_server_address -[44]: https://nodejs.org/api/domain.html +[77]: http://nodejs.org/docs/latest/api/http.html#http_class_http_server -[45]: https://github.com/restify/errors +[78]: https://nodejs.org/api/domain.html -[46]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp +[79]: https://github.com/restify/errors -[47]: https://github.com/delvedor/find-my-way +[80]: https://github.com/delvedor/find-my-way diff --git a/lib/plugins/bodyParser.js b/lib/plugins/bodyParser.js index aaf4d5fac..49170dac8 100644 --- a/lib/plugins/bodyParser.js +++ b/lib/plugins/bodyParser.js @@ -95,6 +95,12 @@ var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; * Limits the amount of memory all fields together (except files) * can allocate in bytes. * The default size is `2 * 1024 * 1024` bytes *(2MB)*. + * @param {Number} [options.arrayLimit=20] - `urlEncodedBodyParser` only. Only + * transform `a[$index]=b` to an array if `$index` is less than `arrayLimit`. + * @param {Boolean} [options.throwOnLimitExceeded=false] - `urlEncodedBodyParser` + * only. If true, throws when `arrayLimit` or `parameterLimit` is exceeded, + * instead of silently dropping the offending params. The error is surfaced + * as an `InvalidContentError`. * @returns {Function} Handler * @example * server.use(restify.plugins.bodyParser({ diff --git a/lib/plugins/formBodyParser.js b/lib/plugins/formBodyParser.js index 45731e8e7..42fac4dbc 100644 --- a/lib/plugins/formBodyParser.js +++ b/lib/plugins/formBodyParser.js @@ -24,6 +24,12 @@ var MIME_TYPE = 'application/x-www-form-urlencoded'; * @public * @function urlEncodedBodyParser * @param {Object} options - an option sobject + * @param {Number} [options.arrayLimit=20] - Only transform `a[$index]=b` + * to an array if `$index` is less than `arrayLimit`. + * @param {Boolean} [options.throwOnLimitExceeded=false] - If true, throws + * when `arrayLimit` or `parameterLimit` is exceeded, instead of silently + * dropping the offending params. The error is surfaced as an + * `InvalidContentError`. * @returns {Function} Handler */ function urlEncodedBodyParser(options) { @@ -42,7 +48,7 @@ function urlEncodedBodyParser(options) { } try { - var params = querystring.parse(req.body); + var params = querystring.parse(req.body, opts); if (opts.mapParams === true) { var keys = Object.keys(params); diff --git a/lib/plugins/query.js b/lib/plugins/query.js index 49aec971f..0148d1617 100644 --- a/lib/plugins/query.js +++ b/lib/plugins/query.js @@ -4,6 +4,7 @@ var qs = require('qs'); var assert = require('assert-plus'); +var errors = require('restify-errors'); /** * Parses the HTTP query string (i.e., `/foo?id=bar&name=mark`). @@ -39,6 +40,9 @@ var assert = require('assert-plus'); * methods, e.g. `?hasOwnProperty=blah`. * @param {Boolean} [options.strictNullHandling=false] - If true, `?a&b=` * results in `{a: null, b: ''}`. Otherwise, `{a: '', b: ''}`. + * @param {Boolean} [options.throwOnLimitExceeded=false] - If true, throws + * (surfaced as a `BadRequestError`) when `arrayLimit` or `parameterLimit` + * is exceeded, instead of silently dropping the offending params. * @returns {Function} Handler * @example * server.use(restify.plugins.queryParser({ mapParams: false })); @@ -53,7 +57,11 @@ function queryParser(options) { return next(); } - req.query = qs.parse(req.getQuery(), opts); + try { + req.query = qs.parse(req.getQuery(), opts); + } catch (e) { + return next(new errors.InvalidContentError(e.message)); + } if (opts.mapParams === true) { Object.keys(req.query).forEach(function forEach(k) { diff --git a/package.json b/package.json index 6b07f155e..1f5cfab96 100644 --- a/package.json +++ b/package.json @@ -107,7 +107,7 @@ "once": "^1.4.0", "pidusage": "^3.0.2", "pino": "^8.7.0", - "qs": "^6.7.0", + "qs": "^6.15.2", "restify-errors": "^8.0.2", "semver": "^7.3.8", "send": "^0.18.0",