HTTP Context Parameter Decorators
This file provides a set of parameter decorators for HTTP controller methods in the @sodacore/core
HTTP module. These decorators allow you to inject specific HTTP context objects (such as request, server, params, query, headers, cookies, body, URL, and method) directly into your handler method parameters by attaching metadata for later resolution.
Features
- Context Injection: Injects HTTP-specific objects (request, server, params, query, headers, cookies, body, URL, method) into controller method parameters.
- Flexible Parameter Selection: Supports injecting entire objects or specific named parameters (e.g., a specific query or cookie).
- Format Support: Allows specifying the format for the request body (JSON or raw text).
- Metadata Management: Stores parameter metadata for each method, enabling the framework to resolve and inject the correct values at runtime.
Usage
import {
Request,
Server,
Params,
Query,
Headers,
Cookies,
Body,
Url,
Method
} from './decorator/context';
class MyHttpController {
async handleRequest(
@Request() req,
@Server() server,
@Params('id') id,
@Query('search') search,
@Headers('authorization') authHeader,
@Cookies('session') sessionCookie,
@Body('json') body,
@Url() url,
@Method() method
) {
// Your logic here
}
}
API
Request(): ParameterDecorator
Injects the HTTP Request
object into the parameter.
Server(): ParameterDecorator
Injects the Bun Server
object into the parameter.
Params(name?: string): ParameterDecorator
Injects the URL params object or a specific parameter by name.
Query(name?: string): ParameterDecorator
Injects the query object or a specific query parameter by name.
Headers(name?: string): ParameterDecorator
Injects the headers object or a specific header by name.
Cookies(name?: string): ParameterDecorator
Injects the cookies object or a specific cookie by name.
Body(format: 'json' | 'raw' = 'json'): ParameterDecorator
Injects the request body, parsed as JSON by default, or as raw text if specified.
Url(): ParameterDecorator
Injects the URL object instance of the request.
Method(): ParameterDecorator
Injects the HTTP method used to access the endpoint.
How It Works
- Each decorator retrieves or creates the method's parameter metadata array.
- It pushes an object describing the parameter's index, type, and any additional options (name, format).
- The metadata is stored using
Utils.setMeta
and is later used by the framework to resolve and inject the correct values when the controller method is called.
Notes
- These decorators are intended for use within HTTP controller classes.
- The framework will automatically resolve and inject the correct context objects based on the metadata at runtime.
- Useful for building clean, declarative HTTP API handlers.