strong-tie/inbound-calls
0
1<h1 align="center">Fastify</h1>2 3## Request4The first parameter of the handler function is `Request`.5 6Request is a core Fastify object containing the following fields:7- `query` - the parsed querystring, its format is specified by8 [`querystringParser`](./Server.md#querystringparser)9- `body` - the request payload, see [Content-Type10 Parser](./ContentTypeParser.md) for details on what request payloads Fastify11 natively parses and how to support other content types12- `params` - the params matching the URL13- [`headers`](#headers) - the headers getter and setter14- `raw` - the incoming HTTP request from Node core15- `server` - The Fastify server instance, scoped to the current [encapsulation16 context](./Encapsulation.md)17- `id` - the request ID18- `log` - the logger instance of the incoming request19- `ip` - the IP address of the incoming request20- `ips` - an array of the IP addresses, ordered from closest to furthest, in the21 `X-Forwarded-For` header of the incoming request (only when the22 [`trustProxy`](./Server.md#factory-trust-proxy) option is enabled)23- `host` - the host of the incoming request (derived from `X-Forwarded-Host`24 header when the [`trustProxy`](./Server.md#factory-trust-proxy) option is25 enabled). For HTTP/2 compatibility it returns `:authority` if no host header26 exists. The host header may return an empty string if `requireHostHeader`27 is false, not provided with HTTP/1.0, or removed by schema validation.28- `hostname` - the hostname derived from the `host` property of29 the incoming request30- `port` - the port from the `host` property, which may refer to31 the port the server is listening on32- `protocol` - the protocol of the incoming request (`https` or `http`)33- `method` - the method of the incoming request34- `url` - the URL of the incoming request35- `originalUrl` - similar to `url`, this allows you to access the36 original `url` in case of internal re-routing37- `is404` - true if request is being handled by 404 handler, false if it is not38- `socket` - the underlying connection of the incoming request39- `context` - Deprecated, use `request.routeOptions.config` instead.40A Fastify internal object. You should not use41it directly or modify it. It is useful to access one special key:42 - `context.config` - The route [`config`](./Routes.md#routes-config) object.43- `routeOptions` - The route [`option`](./Routes.md#routes-options) object44 - `bodyLimit` - either server limit or route limit45 - `config` - the [`config`](./Routes.md#routes-config) object for this route46 - `method` - the http method for the route47 - `url` - the path of the URL to match this route48 - `handler` - the handler for this route49 - `attachValidation` - attach `validationError` to request50 (if there is a schema defined)51 - `logLevel` - log level defined for this route52 - `schema` - the JSON schemas definition for this route53 - `version` - a semver compatible string that defines the version of the endpoint54 - `exposeHeadRoute` - creates a sibling HEAD route for any GET routes55 - `prefixTrailingSlash` - string used to determine how to handle passing /56 as a route with a prefix.57- [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -58 Returns a validation function for the specified schema or http part,59 if any of either are set or cached.60- [.compileValidationSchema(schema, [httpPart])](#compilevalidationschema) -61 Compiles the specified schema and returns a validation function62 using the default (or customized) `ValidationCompiler`.63 The optional `httpPart` is forwarded to the `ValidationCompiler`64 if provided, defaults to `null`.65- [.validateInput(data, schema | httpPart, [httpPart])](#validate) -66 Validates the specified input by using the specified67 schema and returns the serialized payload. If the optional68 `httpPart` is provided, the function will use the serializer69 function given for that HTTP Status Code. Defaults to `null`.70 71### Headers72 73The `request.headers` is a getter that returns an Object with the headers of the74incoming request. You can set custom headers like this:75 76```js77request.headers = {78 'foo': 'bar',79 'baz': 'qux'80}81```82 83This operation will add to the request headers the new values that can be read84calling `request.headers.bar`. Moreover, you can still access the standard85request's headers with the `request.raw.headers` property.86 87> Note: For performance reason on `not found` route, you may see that we will88add an extra property `Symbol('fastify.RequestAcceptVersion')` on the headers.89 90> Note: Using schema validation may mutate the `request.headers` and91`request.raw.headers` objects, causing the headers to become empty.92 93```js94fastify.post('/:params', options, function (request, reply) {95 console.log(request.body)96 console.log(request.query)97 console.log(request.params)98 console.log(request.headers)99 console.log(request.raw)100 console.log(request.server)101 console.log(request.id)102 console.log(request.ip)103 console.log(request.ips)104 console.log(request.host)105 console.log(request.hostname)106 console.log(request.port)107 console.log(request.protocol)108 console.log(request.url)109 console.log(request.routeOptions.method)110 console.log(request.routeOptions.bodyLimit)111 console.log(request.routeOptions.method)112 console.log(request.routeOptions.url)113 console.log(request.routeOptions.attachValidation)114 console.log(request.routeOptions.logLevel)115 console.log(request.routeOptions.version)116 console.log(request.routeOptions.exposeHeadRoute)117 console.log(request.routeOptions.prefixTrailingSlash)118 console.log(request.routeOptions.logLevel)119 request.log.info('some info')120})121```122### .getValidationFunction(schema | httpPart)123<a id="getvalidationfunction"></a>124 125By calling this function using a provided `schema` or `httpPart`,126it will return a `validation` function that can be used to127validate diverse inputs. It returns `undefined` if no128serialization function was found using either of the provided inputs.129 130This function has property errors. Errors encountered during the last validation131are assigned to errors132 133```js134const validate = request135 .getValidationFunction({136 type: 'object',137 properties: {138 foo: {139 type: 'string'140 }141 }142 })143console.log(validate({ foo: 'bar' })) // true144console.log(validate.errors) // null145 146// or147 148const validate = request149 .getValidationFunction('body')150console.log(validate({ foo: 0.5 })) // false151console.log(validate.errors) // validation errors152```153 154See [.compileValidationSchema(schema, [httpStatus])](#compilevalidationschema)155for more information on how to compile validation function.156 157### .compileValidationSchema(schema, [httpPart])158<a id="compilevalidationschema"></a>159 160This function will compile a validation schema and161return a function that can be used to validate data.162The function returned (a.k.a. _validation function_) is compiled163by using the provided [`SchemaController#ValidationCompiler`](./Server.md#schema-controller).164A `WeakMap` is used to cache this, reducing compilation calls.165 166The optional parameter `httpPart`, if provided, is forwarded directly167the `ValidationCompiler`, so it can be used to compile the validation168function if a custom `ValidationCompiler` is provided for the route.169 170This function has property errors. Errors encountered during the last validation171are assigned to errors172 173```js174const validate = request175 .compileValidationSchema({176 type: 'object',177 properties: {178 foo: {179 type: 'string'180 }181 }182 })183console.log(validate({ foo: 'bar' })) // true184console.log(validate.errors) // null185 186// or187 188const validate = request189 .compileValidationSchema({190 type: 'object',191 properties: {192 foo: {193 type: 'string'194 }195 }196 }, 200)197console.log(validate({ hello: 'world' })) // false198console.log(validate.errors) // validation errors199```200 201Note that you should be careful when using this function, as it will cache202the compiled validation functions based on the schema provided. If the203schemas provided are mutated or changed, the validation functions will not204detect that the schema has been altered and for instance it will reuse the205previously compiled validation function, as the cache is based on206the reference of the schema (Object) previously provided.207 208If there is a need to change the properties of a schema, always opt to create209a totally new schema (object), otherwise the implementation will not benefit from210the cache mechanism.211 212Using the following schema as an example:213```js214const schema1 = {215 type: 'object',216 properties: {217 foo: {218 type: 'string'219 }220 }221}222```223 224*Not*225```js226const validate = request.compileValidationSchema(schema1)227 228// Later on...229schema1.properties.foo.type. = 'integer'230const newValidate = request.compileValidationSchema(schema1)231 232console.log(newValidate === validate) // true233```234 235*Instead*236```js237const validate = request.compileValidationSchema(schema1)238 239// Later on...240const newSchema = Object.assign({}, schema1)241newSchema.properties.foo.type = 'integer'242 243const newValidate = request.compileValidationSchema(newSchema)244 245console.log(newValidate === validate) // false246```247 248### .validateInput(data, [schema | httpStatus], [httpStatus])249<a id="validate"></a>250 251This function will validate the input based on the provided schema,252or HTTP part passed. If both are provided, the `httpPart` parameter253will take precedence.254 255If there is not a validation function for a given `schema`, a new validation256function will be compiled, forwarding the `httpPart` if provided.257 258```js259request260 .validateInput({ foo: 'bar'}, {261 type: 'object',262 properties: {263 foo: {264 type: 'string'265 }266 }267 }) // true268 269// or270 271request272 .validateInput({ foo: 'bar'}, {273 type: 'object',274 properties: {275 foo: {276 type: 'string'277 }278 }279 }, 'body') // true280 281// or282 283request284 .validateInput({ hello: 'world'}, 'query') // false285```286 287See [.compileValidationSchema(schema, [httpStatus])](#compileValidationSchema)288for more information on how to compile validation schemas.289 