Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add request.routeOptions object #4397

Merged
merged 20 commits into from Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 10 additions & 2 deletions docs/Reference/Request.md
Expand Up @@ -43,7 +43,11 @@ Request is a core Fastify object containing the following fields:
- `routeConfig` - The route [`config`](./Routes.md#routes-config)
object.
- `routeOptions` - The route [`option`](./Routes.md#routes-options) object
- `bodyLimit` - either server limit or route limit
- `bodyLimit` - either get server limit or route limit
- `method` - get http method
- `url` - get the path of the URL to match this route
- `attachValidation` - attach `validationError` to request, if there is a schema
- `logLevel` - get log level for this route.
- [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -
Returns a validation function for the specified schema or http part,
if any of either are set or cached.
Expand Down Expand Up @@ -93,7 +97,11 @@ fastify.post('/:params', options, function (request, reply) {
console.log(request.url)
console.log(request.routerMethod)
console.log(request.routeOptions.bodyLimit)
console.log(request.routerPath)
console.log(request.routeOptions.method)
console.log(request.routeOptions.url)
console.log(request.routeOptions.attachValidation)
console.log(request.routeOptions.logLevel)
console.log(request.routerPath.logLevel)
request.log.info('some info')
})
```
Expand Down
47 changes: 35 additions & 12 deletions lib/request.js
Expand Up @@ -137,6 +137,21 @@ function buildRequestWithTrustProxy (R, trustProxy) {

return _Request
}
/**
*
* @param {object} target
* @returns {Proxy}
*/
function readOnly (target) {
return new Proxy(target, {
get (target, key) {
return target[key]
},
set (_, key) {
throw new Error(`property ${key} is immutable`)
}
})
}

Object.defineProperties(Request.prototype, {
server: {
Expand Down Expand Up @@ -168,11 +183,19 @@ Object.defineProperties(Request.prototype, {
routeOptions: {
get () {
const context = this[kRouteContext]
const serverLimit = context.server.initialConfig.bodyLimit
const routeLimit = context._parserOptions.limit
return {
bodyLimit: ((routeLimit || serverLimit))
const serverLimit = context.server.initialConfig.bodyLimit
const options = {
method: context.config.method,
debadutta98 marked this conversation as resolved.
Show resolved Hide resolved
url: this.raw.url,
debadutta98 marked this conversation as resolved.
Show resolved Hide resolved
bodyLimit: (routeLimit || serverLimit),
attachValidation: context.attachValidation,
logLevel: context.logLevel
}
return readOnly(options)
debadutta98 marked this conversation as resolved.
Show resolved Hide resolved
},
set () {
throw new Error('routerOptions is immutable')
}
},
routerMethod: {
Expand Down Expand Up @@ -258,13 +281,13 @@ Object.defineProperties(Request.prototype, {
}

const validatorCompiler = this[kRouteContext].validatorCompiler ||
this.server[kSchemaController].validatorCompiler ||
(
// We compile the schemas if no custom validatorCompiler is provided
// nor set
this.server[kSchemaController].setupValidator(this.server[kOptions]) ||
this.server[kSchemaController].validatorCompiler
)
this.server[kSchemaController].validatorCompiler ||
debadutta98 marked this conversation as resolved.
Show resolved Hide resolved
(
// We compile the schemas if no custom validatorCompiler is provided
// nor set
this.server[kSchemaController].setupValidator(this.server[kOptions]) ||
this.server[kSchemaController].validatorCompiler
)

const validateFn = validatorCompiler({
schema,
Expand Down Expand Up @@ -301,8 +324,8 @@ Object.defineProperties(Request.prototype, {

// We cannot compile if the schema is missed
if (validate == null && (schema == null ||
typeof schema !== 'object' ||
Array.isArray(schema))
typeof schema !== 'object' ||
debadutta98 marked this conversation as resolved.
Show resolved Hide resolved
Array.isArray(schema))
) {
throw new FST_ERR_REQ_INVALID_VALIDATION_INVOCATION(httpPart)
}
Expand Down
42 changes: 42 additions & 0 deletions test/request-error.test.js
@@ -1,6 +1,7 @@
'use strict'

const { connect } = require('net')
const sget = require('simple-get').concat
const t = require('tap')
const test = t.test
const Fastify = require('..')
Expand Down Expand Up @@ -313,3 +314,44 @@ test('default clientError replies with bad request on reused keep-alive connecti
client.write('\r\n\r\n')
})
})

test('request.routeOptions should be immutable', t => {
t.plan(7)
const fastify = Fastify()
const handler = function (req, res) {
t.equal('POST', req.routeOptions.method)
t.equal('/', req.routeOptions.url)
try {
req.routeOptions.bodyLimit = 1001
t.fail('property bodyLimit is immutable')
} catch (err) {
t.ok(err)
}
try {
req.routeOptions = null
t.fail('routerOptions is immutable')
} catch (err) {
t.ok(err)
}
res.send({ hello: 'world' })
}
fastify.post('/', {
bodyLimit: 1000,
handler
})
fastify.listen({ port: 0 }, function (err) {
t.error(err)
t.teardown(() => { fastify.close() })

sget({
method: 'POST',
url: 'http://localhost:' + fastify.server.address().port,
headers: { 'Content-Type': 'application/json' },
body: [],
json: true
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 200)
})
})
})
4 changes: 2 additions & 2 deletions test/types/request.test-d.ts
Expand Up @@ -17,7 +17,7 @@ import fastify, {
} from '../../fastify'
import { RequestParamsDefault, RequestHeadersDefault, RequestQuerystringDefault } from '../../types/utils'
import { FastifyLoggerInstance } from '../../types/logger'
import { FastifyRequest } from '../../types/request'
import { FastifyRequest, RequestRouteOptions } from '../../types/request'
import { FastifyReply } from '../../types/reply'
import { FastifyInstance } from '../../types/instance'
import { RouteGenericInterface } from '../../types/route'
Expand Down Expand Up @@ -66,7 +66,7 @@ const getHandler: RouteHandler = function (request, _reply) {
expectType<string>(request.method)
expectType<string>(request.routerPath)
expectType<string>(request.routerMethod)
expectType<number>(request.routeBodyLimit)
expectType<Readonly<RequestRouteOptions>>(request.routeOptions)
expectType<boolean>(request.is404)
expectType<string>(request.hostname)
expectType<string>(request.ip)
Expand Down
10 changes: 9 additions & 1 deletion types/request.d.ts
Expand Up @@ -20,6 +20,14 @@ export interface ValidationFunction {
errors?: null | ErrorObject[];
}

export interface RequestRouteOptions {
method: string,
url: string,
bodyLimit:number,
attachValidation:boolean,
logLevel:string
}

/**
* FastifyRequest is an instance of the standard http or http2 request objects.
* It defaults to http.IncomingMessage, and it also extends the relative request object.
Expand Down Expand Up @@ -66,7 +74,7 @@ export interface FastifyRequest<RouteGeneric extends RouteGenericInterface = Rou
readonly method: string;
readonly routerPath: string;
readonly routerMethod: string;
readonly routeBodyLimit: number;
readonly routeOptions: Readonly<RequestRouteOptions>
readonly is404: boolean;
readonly socket: RawRequest['socket'];

Expand Down