RequestContext

RequestContext

The Context object is instantiated for each request and is automatically destroyed after request is done, all middleware and routing is using the context.

It wraps access to all request/response runtime properties and supports returning properly formatted responses.

Constructor

new RequestContext(req, res, optionsopt)

Source:
Parameters:
Name Type Attributes Description
req IncomingMessage
res OutgoingMessage
options object <optional>
Properties
Name Type Attributes Description
trustProxy boolean <optional>

trus proxy headers

Members

auth :{type:string, token:string, user:string, password:string}

Description:
  • Parse and return Authorization header as an object

    • type - first word, Basic, Bearer or other type
    • token - the value after type field, for Basic type the value is decoded from base64
    • user - for type Basic it is the user name part before :
    • password - for type Basic it is the second part after :
Source:

body :undefined | string | object | Buffer

Description:
  • Body object

Source:

closed :boolean

Description:
  • true if the response has been closed, destroyed, written...

Source:

contentType :string

Description:
  • Content type form the header, only MIME type, eg. text/json

Source:

domain :string

Description:
  • Domain name from the current hostname

Source:

host :string

Description:
  • Current host header, if options.trustProxy is true uses proxy headers

Source:

hostname :string

Description:
  • Current host name without port

Source:

ip :string

Description:
  • Current IP address, if options.trustProxy is true uses proxy headers

Source:

ips :Array.<string>

Description:
  • List of all IP addresses from the proxy headers

Source:

location :string

Description:
  • Full location as host/path

Source:

method :string

Description:
  • HTTP method

Source:

params :object

Description:
  • Route named or wildcard params from the path

Source:

path :string

Description:
  • request path only

Source:

paths :Array.<string>

Description:
  • an array with the path split by /, leading empty item removed

Source:

proto :string

Description:
  • Current protocol without colon, ex. http, https, if options.trustProxy is true uses proxy headers

Source:

query :object

Description:
  • Query object

Source:

req :IncomingMessage

Description:
  • Current request

Source:

reqID :string

Description:
  • semi-unique request ID, per process

Source:

res :OutgoingMessage

Description:
  • Current response

Source:
Description:
  • query part from url, without leading question mark

Source:

session :{id:string, exp:number}

Description:
  • parsed or created session

Source:

time :number

Description:
  • request creation timestamp

Source:

url :string

Description:
  • full request url from the IncomingMessage

Source:

user :object

Description:
  • Currrent authenticated user, on set property userId is created for faster access, it is not cleared on reseting the user to be logged by access logger

Source:

userId :string

Description:
  • when user is set this property will contain user.id

Source:

Methods

appendHeader(name, value) → {this}

Description:
  • No-exceptions version of res.appendHeader

Source:
Parameters:
Name Type Description
name string
value string | Array.<string>
Returns:
Type Description
this
Description:
  • Return a cookie value by name from the reauest

Source:
Parameters:
Name Type Description
name string

cookie name

Returns:
Type Description
string | undefined

value

destroy()

Description:
  • Destroy the context, free memory and resources, call all destroy hooks, async hooks should expect properties being empty

Source:

emit(hook, dataopt)

Description:
  • Emit hooks by name, promises are resolved but not awaited, all listeners are executed in the order of registration

Source:
Parameters:
Name Type Attributes Description
hook string
data any <optional>
Example

DB op will finish in the background

context.on("event", async (ctx, data) => {
    await db.update(......)
    console.log("done!")
})

context.emit("event", data)
...
'done!'

format(text) → {string}

Description:
  • Replace placeholders in the given text with details fron the context

Source:
Parameters:
Name Type Description
text string

it may contain placeholders in the form: @name@:

  • HOST - full host name from header
  • IP - remote IP address
  • DOMAIN - domain from the hostname
  • PATH - full path
  • PATH[1-9] - path starting from given index till the end, eg.: /a/b/c/d, PATH2 will be b/c/d
  • URL - full url
  • BASE - basename from the path no extention
  • FILE - base file name with extention
  • DIR - directory name only
  • SUBDIR - last part of the directory path
  • EXT - file extention
  • SEARCH - search from the full url
Returns:
Type Description
string

all known placeholders are replaced

json(body) → {this}

Description:
  • Send JSON response

Source:
Parameters:
Name Type Description
body string | object | array

body

Returns:
Type Description
this

on(hook, callback) → {this}

Description:
  • Add a handler for a hook, this is similar to event emmiters

Source:
Parameters:
Name Type Description
hook string

hook name

callback function()

(context, data)

Returns:
Type Description
this

Supported hooks:

  • destroy - called when context is destroyed
  • error - fatal error occured

redirect(status, url) → {this}

Description:
  • Send redirect response

Source:
Parameters:
Name Type Description
status string | number

301...308

url string

location

Returns:
Type Description
this

reply(err, data) → {this}

Description:
  • Send error if not empty or the data as JSON, uses send

Source:
Parameters:
Name Type Description
err undefined | object | Error

err

data string | object | array

body if no error

Returns:
Type Description
this

send(status, bodyopt, typeopt) → {this}

Description:
  • Send final response with status and optional body. NOTE: After this call the context becomes empty (calls destroy on response end), all properties are reset.

Source:
Parameters:
Name Type Attributes Description
status number | string

resonse HTTP status

body string | Buffer <optional>
type string <optional>

content type

Returns:
Type Description
this

sendFile(file, optionsopt, nextopt) → {this}

Description:
  • Stream a file to response, close on error or finish

Source:
Parameters:
Name Type Attributes Description
file string
options object <optional>
Properties
Name Type Attributes Default Description
root string <optional>

root directory

maxAge number <optional>

file cache age in ms

noCache boolean <optional>

return no-cache header

lastModified boolean <optional>

send Last-Modified header

start number <optional>

file start offset

end number <optional>

file end offset

etag boolean <optional>

generate and check weak etag

index string <optional>

index file to use for directories

precompressed regexp <optional>

if path matched serve precompressed file if exists

encoding string <optional>
gzip

precompressed encoding type: gzip, br, zstd

next function() <optional>

next middleware if not found

Returns:
Type Description
this

setCookie(name, value, optionsopt) → {this}

Description:
  • Add cookies to response's Set-Cookies

Source:
Parameters:
Name Type Attributes Description
name string

cookie name

value string

cookie value

options object <optional>

cookie options for module:lib.toCookie

Returns:
Type Description
this

setHeader(name, value) → {this}

Description:
  • No-exceptions version of res.setHeader

Source:
Parameters:
Name Type Description
name string
value any
Returns:
Type Description
this

setUrl(urlopt) → {this}

Description:
  • Replace current request path including updating request options. It is used in routing and vhosting.

Source:
Parameters:
Name Type Attributes Description
url string <optional>

new full request url, if new url has no ? then the original search is preserved

Returns:
Type Description
this

stat(file, optionsopt, callback)

Description:
  • Wrapper around fs.stat, handles index file in case if the file points to a directory and precompressed encoding

Source:
Parameters:
Name Type Attributes Description
file string
options object <optional>

same as in RequestContext.sendFile

Properties
Name Type Attributes Default Description
index string <optional>

index file to use for directories

precompressed regexp <optional>

if path matched serve precompressed file if exists

encoding string <optional>
gzip

precompressed encoding type: gzip, br, zstd

callback function()

var(key, valueopt) → {any}

Description:
  • Generic store for arbitrary variables to keep in the context, not to be logged

Source:
Parameters:
Name Type Attributes Description
key any

key name, it uses Map so any value can be used

value any <optional>

value to store, if no value just return current value if exists

Returns:
Type Description
any
  • old value