Context
Context is an object that contains information and useful methods related to the current request. Context instances are different between different requests.
Context Content
Name | Purpose | Condition |
---|---|---|
context.logger | Logger object used for logging | Always present |
context.executeId | Unique identifier of the current request | Always present |
context.headers | Headers of the current request | Always present |
context.path | Path of the current request | Always present |
context.detail.request | Current HTTP request object | Only present when called via HTTP |
context.detail.response | Current HTTP response object | Only present when called via HTTP |
context.detail.ip | IP address of the current request | Only present when called via HTTP |
context.detail.fullurl | Real URL object of the current request | Only present when called via HTTP |
Detail
The content in context.detail
is not present in all environments. Typically, this content is only available during HTTP execution. The most common scenario is that this content does not exist during testing and is only present in real HTTP requests.
Extending Context
You can also extend the Context. You can think of it as a “globalThis” shared between requests. For example, you can read user data in middleware and attach it to context.user
. Then, in your API, you can directly access the current user’s information through context.user
.
Also, don’t forget to edit the /src/context.ts
file to add the types for the extended Context! Note that extending the Context type does not mean the data actually exists in the Context. Besides the default properties of Context, you need to write code to attach the data to the Context.