Skip to content

Commit

Permalink
feat: expose route context through request object
Browse files Browse the repository at this point in the history
  • Loading branch information
metcoder95 committed Sep 5, 2022
1 parent be19fc9 commit 6aa3fff
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
36 changes: 34 additions & 2 deletions lib/context.js
Expand Up @@ -13,7 +13,7 @@ const {
kRouteByFastify,
kRequestValidateWeakMap,
kReplySerializeWeakMap,
// kPublicRouteContext
kPublicRouteContext
} = require('./symbols.js')

// Objects that holds the context of every request
Expand Down Expand Up @@ -57,17 +57,49 @@ function Context ({
this[kFourOhFourContext] = null
this.attachValidation = attachValidation
this[kReplySerializerDefault] = replySerializer
this.schemaErrorFormatter = schemaErrorFormatter || server[kSchemaErrorFormatter] || defaultSchemaErrorFormatter
this.schemaErrorFormatter =
schemaErrorFormatter ||
server[kSchemaErrorFormatter] ||
defaultSchemaErrorFormatter
this[kRouteByFastify] = isFastify

this[kRequestValidateWeakMap] = null
this[kReplySerializeWeakMap] = null
this.validatorCompiler = validatorCompiler || null
this.serializerCompiler = serializerCompiler || null

// Route + Userland configurations for the route
this[kPublicRouteContext] = getPublicRouteContext(this)

this.server = server
}

function getPublicRouteContext (context) {
return Object.create(null, {
schema: {
enumerable: true,
get () {
return context.schema
}
},
config: {
enumerable: true,
get () {
return context.config
}
},
logLevel: {
enumerable: true,
set (level) {
context.logLevel = level
},
get () {
return context.logLevel
}
}
})
}

function defaultSchemaErrorFormatter (errors, dataVar) {
let text = ''
const separator = ', '
Expand Down
8 changes: 7 additions & 1 deletion lib/request.js
Expand Up @@ -12,7 +12,8 @@ const {
kSchemaController,
kOptions,
kRequestValidateWeakMap,
kRouteContext
kRouteContext,
kPublicRouteContext
} = require('./symbols')
const { FST_ERR_REQ_INVALID_VALIDATION_INVOCATION } = require('./errors')

Expand Down Expand Up @@ -163,6 +164,11 @@ Object.defineProperties(Request.prototype, {
return this[kRouteContext].config.method
}
},
routeContext: {
get () {
return this[kRouteContext][kPublicRouteContext]
}
},
is404: {
get () {
return this[kRouteContext].config.url === undefined
Expand Down

0 comments on commit 6aa3fff

Please sign in to comment.