API Reference

Complete API reference for @hazeljs/core. All symbols listed below are exported from the package and can be imported directly:

import { Controller, Get, Injectable, HazelModule /* ... */ } from '@hazeljs/core';

Application

HazelApp

The main application class. Creates and bootstraps a HazelJS application from a root module.

class HazelApp {
  constructor(rootModule: Type<unknown>)
  listen(port: number): Promise<void>
  addEarlyHandler(path: string, handler: EarlyHttpHandler): void
  addProxyHandler(pathPrefix: string, handler: ProxyHandler): void
}

type EarlyHttpHandler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
type ProxyHandler = (req: IncomingMessage, res: ServerResponse, context: RequestContext) => Promise<boolean>;
  • addEarlyHandler: Register a handler that runs before body parsing (e.g. for GraphQL subscriptions).
  • addProxyHandler: Register a proxy handler for path prefixes (e.g. API gateway). Runs after body parsing.

Usage:

import { HazelApp } from '@hazeljs/core';
import { AppModule } from './app.module';

const app = new HazelApp(AppModule);
await app.listen(3000);

Module Decorators

@HazelModule(options)

Class decorator that defines a module.

function HazelModule(options: ModuleOptions): ClassDecorator
interface ModuleOptions {
  imports?: Type[];        // Modules to import
  controllers?: Type[];    // Controllers to register
  providers?: Type[];      // Providers (services) to register
  exports?: Type[];        // Providers to make available to importing modules
}

Usage:

@HazelModule({
  imports: [UserModule],
  controllers: [AppController],
  providers: [AppService],
  exports: [AppService],
})
export class AppModule {}

@Module(options)

Alias for @HazelModule. Identical behavior.

getModuleMetadata(target)

Returns module metadata for a given class.

function getModuleMetadata(target: object): ModuleOptions | undefined

Controller Decorators

@Controller(pathOrOptions)

Class decorator that marks a class as a controller with a route prefix.

function Controller(options: string | ControllerOptions): ClassDecorator
interface ControllerOptions {
  path: string;
  version?: string;
}

Usage:

@Controller('users')           // string form
@Controller({ path: '/users' }) // object form

HTTP Method Decorators

All method decorators accept an optional path string or options object.

@Get(path?)

function Get(options?: string | { path?: string }): MethodDecorator

@Post(path?)

function Post(options?: string | { path?: string }): MethodDecorator

@Put(path?)

function Put(options?: string | { path?: string }): MethodDecorator

@Delete(path?)

function Delete(options?: string | { path?: string }): MethodDecorator

@Patch(path?)

function Patch(options?: string | { path?: string }): MethodDecorator

Usage:

@Controller('users')
export class UserController {
  @Get()          // GET /users
  @Get(':id')     // GET /users/:id
  @Post()         // POST /users
  @Put(':id')     // PUT /users/:id
  @Delete(':id')  // DELETE /users/:id
  @Patch(':id')   // PATCH /users/:id
}

Parameter Decorators

@Body(dtoType?)

Extracts the request body. Optionally validates against a DTO class.

function Body(dtoType?: Type<unknown>): ParameterDecorator

Usage:

@Post()
create(@Body() data: CreateUserDto) { }

@Post()
create(@Body(CreateUserDto) data: CreateUserDto) { }  // with validation

@Param(name, pipe?)

Extracts a route parameter by name.

function Param(paramName: string, pipe?: Type<PipeTransform>): ParameterDecorator

Usage:

@Get(':id')
findOne(@Param('id') id: string) { }

@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { }  // with pipe

@Query(name?, pipe?)

Extracts a query parameter. If no name is given, returns all query params as an object.

function Query(paramName?: string, pipe?: Type<PipeTransform>): ParameterDecorator

Usage:

@Get()
findAll(@Query('page') page: string, @Query('limit') limit: string) { }

@Get()
findAll(@Query() query: Record<string, string>) { }  // all query params

@Req()

Injects the raw request object.

function Req(): ParameterDecorator

Usage:

@Get()
findAll(@Req() request: Request) { }

@Request()

Alias for @Req(). Injects the raw request object. Same signature and behavior.

@Res()

Injects the raw response object for manual response handling.

function Res(): ParameterDecorator

Usage:

@Get()
findAll(@Res() response: Response) {
  response.status(200).json({ message: 'OK' });
}

@Headers(name?)

Extracts request headers. If a name is given, returns that single header value. Otherwise returns all headers.

function Headers(headerName?: string): ParameterDecorator

Usage:

@Get()
findAll(@Headers('authorization') auth: string) { }

@Get()
findAll(@Headers() headers: Record<string, string>) { }

@Inject(token?)

Injects a provider by token (string, symbol, or class).

function Inject(token?: string | symbol | Type<unknown>): ParameterDecorator

Usage:

constructor(@Inject('CONFIG') private config: any) { }

@Ip()

Injects the client IP address (from socket or x-forwarded-for header).

function Ip(): ParameterDecorator

Usage:

@Get('info')
info(@Ip() ip: string) { }

@Host()

Injects the request host header.

function Host(): ParameterDecorator

Usage:

@Get('info')
info(@Host() host: string) { }

@Session()

Injects req.session when session middleware (e.g. express-session) is used. Otherwise undefined.

function Session(): ParameterDecorator

Usage:

@Get('cart')
getCart(@Session() session: { cart?: string[] }) { }

@Optional()

Marks a parameter as optional. When the underlying source (query, param, header) is missing, injects undefined.

function Optional(): ParameterDecorator

Usage:

@Get()
findAll(@Optional() @Query('page') page?: string) { }

Response Decorators

@HttpCode(statusCode)

Sets the HTTP status code for the response.

function HttpCode(statusCode: number): MethodDecorator

Usage:

@Post()
@HttpCode(201)
create(@Body() dto: CreateUserDto) { }

@Delete(':id')
@HttpCode(204)
remove(@Param('id') id: string) { }

@Header(name, value)

Sets a response header. Can be applied multiple times.

function Header(name: string, value: string): MethodDecorator

Usage:

@Get()
@Header('Cache-Control', 'no-cache')
@Header('X-Custom', 'value')
findAll() { }

@Redirect(url, statusCode?)

Redirects the response to a different URL.

function Redirect(url: string, statusCode?: number): MethodDecorator
// statusCode defaults to 302

Usage:

@Get('old')
@Redirect('/new', 301)
oldRoute() { }

@Public()

Marks a controller or method as public (no auth required). Guards should check Reflect.getMetadata('hazel:public', target, propertyKey) and allow the request when true.

function Public(): ClassDecorator & MethodDecorator

@SkipAuth()

Alias for @Public(). Use to skip auth for specific routes (e.g. login, health).

@Timeout(ms)

Per-route timeout in milliseconds. If the handler runs longer, the request fails with 408 Request Timeout (RequestTimeoutError).

function Timeout(ms: number): MethodDecorator

Usage:

@Get('slow')
@Timeout(5000)
slowQuery() { }

@Retry(options)

Retries the handler on failure. Options: count, delay?, retryIf?. Uses RetryInterceptor under the hood.

function Retry(options: RetryDecoratorOptions): MethodDecorator
interface RetryDecoratorOptions {
  count: number;
  delay?: number;
  retryIf?: (err: Error) => boolean;
}

Usage:

@Get('flaky')
@Retry({ count: 3, delay: 100 })
flaky() { }

@ApiTags(...tags)

Attaches OpenAPI tags to a controller or method (for doc generation, e.g. with @hazeljs/swagger).

function ApiTags(...tags: string[]): ClassDecorator & MethodDecorator

@ApiOperation(options | string)

Attaches OpenAPI operation metadata (summary, description, operationId). Pass an object or a string (used as summary).

function ApiOperation(options: ApiOperationOptions | string): MethodDecorator
interface ApiOperationOptions {
  summary?: string;
  description?: string;
  operationId?: string;
}

@AITask(options)

Marks a method as an AI task. Options: name, prompt, provider, model, outputType. Used by AI-oriented packages (e.g. RAG, agents).

function AITask(options: {
  name: string;
  prompt: string;
  provider: string;
  model: string;
  outputType: string;
}): MethodDecorator

Custom metadata and parameter decorators

SetMetadata(key, value)

Attaches arbitrary key-value metadata to a class or method. Stored under hazel:meta:<key> so it does not collide with framework keys. Guards, interceptors, or other components can read it with getMetadata(key, target, propertyKey?).

function SetMetadata(key: string, value: unknown): ClassDecorator & MethodDecorator

Usage:

@SetMetadata('roles', ['admin'])
class AdminController { }

class UserController {
  @SetMetadata('roles', ['user'])
  @Get('profile')
  getProfile() { }
}

getMetadata(key, target, propertyKey?)

Reads custom metadata set with SetMetadata. Use when building guards or interceptors that need per-class or per-method configuration.

function getMetadata<T>(key: string, target: object, propertyKey?: string | symbol): T | undefined

Usage:

const roles = getMetadata<string[]>('roles', SomeController);
const methodRoles = getMetadata<string[]>('roles', SomeController.prototype, 'getProfile');

createParamDecorator(resolve)

Creates a custom parameter decorator that injects a value computed from the request. The resolver is called at request time with (req, context, container) and can return a value or a Promise.

function createParamDecorator<T>(
  resolve: (req: Request, context: RequestContext, container: Container) => T | Promise<T>
): ParameterDecorator

Usage:

import { createParamDecorator } from '@hazeljs/core';

const CurrentUser = createParamDecorator((_req, ctx) => ctx.user);

@Get('profile')
getProfile(@CurrentUser user: User) {
  return user;
}

Apply the decorator without parentheses: @CurrentUser, not @CurrentUser().

CUSTOM_METADATA_PREFIX

Constant 'hazel:meta:'. Custom metadata from SetMetadata is stored under this prefix plus the key. Use getMetadata() instead of raw Reflect.getMetadata() unless you need the low-level key.

ParamDecoratorContext

Type describing the arguments passed to a custom param decorator’s resolver:

interface ParamDecoratorContext {
  req: Request;
  context: RequestContext;
  container: Container;
}

Provider Decorators

@Injectable(options?)

Marks a class as injectable (can be managed by the DI container).

function Injectable(options?: InjectableOptions): ClassDecorator
interface InjectableOptions {
  scope?: 'singleton' | 'transient' | 'request';
}

Usage:

@Injectable()                              // default: singleton
@Injectable({ scope: 'transient' })        // new instance per injection
@Injectable({ scope: 'request' })          // new instance per HTTP request

@Service(options?)

Alias for @Injectable with additional repository metadata support.

function Service(options?: ServiceOptions): ClassDecorator
interface ServiceOptions {
  scope?: 'singleton' | 'transient' | 'request';
}

Guard, Interceptor & Pipe Decorators

@UseGuards(...guards)

Applies guards to a controller or method.

function UseGuards(...guards: Type<CanActivate>[]): ClassDecorator & MethodDecorator
interface CanActivate {
  canActivate(context: ExecutionContext): Promise<boolean> | boolean;
}

interface ExecutionContext {
  switchToHttp(): {
    getRequest(): unknown;
    getResponse(): unknown;
  };
}

Usage:

@Controller('admin')
@UseGuards(AuthGuard)
export class AdminController { }

@Get('secret')
@UseGuards(RoleGuard)
getSecret() { }

@UseInterceptors(...interceptors)

Applies interceptors to a controller or method.

function UseInterceptors(
  ...interceptors: (Type<Interceptor> | InterceptorMetadata)[]
): ClassDecorator & MethodDecorator

@UsePipes(...pipes)

Applies pipes to a controller or method.

function UsePipes(
  ...pipes: (Type<PipeTransform> | PipeMetadata)[]
): ClassDecorator & MethodDecorator

Routing

@Version(version)

Sets the API version for a controller.

function Version(version: string): ClassDecorator
enum VersioningType {
  URI = 'uri',
  HEADER = 'header',
  MEDIA_TYPE = 'media_type',
}

Usage:

@Controller('users')
@Version('1')
export class UserV1Controller { }

DI Container

Container

Singleton DI container that manages provider registration and resolution.

class Container {
  static getInstance(): Container
  static createTestInstance(): Container
  register<T>(token: InjectionToken<T>, instance: T): void
  registerProvider<T>(provider: Provider<T>): void
  resolve<T>(token: InjectionToken<T>, requestId?: string): T
  clearRequestScope(requestId: string): void
}

Scope

enum Scope {
  SINGLETON = 'singleton',
  TRANSIENT = 'transient',
  REQUEST = 'request',
}

Provider

interface Provider<T = unknown> {
  token: InjectionToken<T>;
  useClass?: Type<T>;
  useValue?: T;
  useFactory?: (...args: unknown[]) => T | Promise<T>;
  scope?: Scope;
  inject?: InjectionToken[];
}

Error Classes

All error classes extend HttpError. Each class has an Exception alias for convenience.

HttpError

class HttpError extends Error {
  constructor(statusCode: number, message: string, errors?: string[])
  readonly statusCode: number;
  readonly errors?: string[];
}
ClassAliasStatus CodeDefault Message
BadRequestErrorBadRequestException400
UnauthorizedErrorUnauthorizedException401'Unauthorized'
ForbiddenErrorForbiddenException403'Forbidden'
NotFoundErrorNotFoundException404'Not Found'
RequestTimeoutError408'Request Timeout'
ConflictErrorConflictException409
InternalServerErrorInternalServerErrorException500'Internal Server Error'

Usage:

import { NotFoundException } from '@hazeljs/core';

throw new NotFoundException('User not found');
throw new NotFoundException();  // uses default message

Pipes

PipeTransform

Interface for creating custom pipes.

abstract class PipeTransform {
  abstract transform(value: unknown, context: RequestContext): unknown | Promise<unknown>;
}

ValidationPipe

Built-in pipe that validates request data against a DTO class using class-validator.

class ValidationPipe extends PipeTransform {
  transform(value: unknown, context: RequestContext): Promise<unknown>
}

ParseIntPipe

Converts a string parameter to an integer. Throws BadRequestError if conversion fails.

class ParseIntPipe extends PipeTransform {
  transform(value: unknown, context: RequestContext): number
}

ValidationError

Error class thrown by ValidationPipe when validation fails. Extends Error and includes validation details.

class ValidationError extends Error {
  constructor(message: string, errors?: string[])
}

Interceptors

Interceptor

Interface for creating custom interceptors.

abstract class Interceptor {
  abstract intercept(context: RequestContext, next: () => Promise<unknown>): Promise<unknown>;
}

RetryInterceptor

Built-in interceptor that retries the handler on failure. Configured via the @Retry() decorator (see Controllers for usage). Reads context.retryOptions (count, delay, optional retryIf). When you use @Retry({ count: 3 }) on a method, the framework attaches this interceptor automatically.

class RetryInterceptor implements Interceptor

Exception Filters

ExceptionFilter

Interface for creating custom exception filters.

interface ExceptionFilter<T = unknown> {
  catch(exception: T, host: ArgumentsHost): void;
}

@Catch(...exceptions)

Decorator that binds an exception filter to specific exception types.

function Catch(...exceptions: Type<Error>[]): ClassDecorator

ArgumentsHost

interface ArgumentsHost {
  switchToHttp(): {
    getRequest(): unknown;
    getResponse(): unknown;
  };
}

ArgumentsHostImpl

Concrete implementation of ArgumentsHost for use in custom exception filters.

getFilterExceptions(filter)

Returns the exception types that an exception filter handles.

function getFilterExceptions(filter: object): Array<new (...args: unknown[]) => unknown>

HttpExceptionFilter

Built-in exception filter for HttpError and its subclasses. Formats errors as JSON with statusCode and message.

class HttpExceptionFilter implements ExceptionFilter<HttpError>

Usage:

@Catch(HttpError)
export class MyHttpExceptionFilter implements ExceptionFilter<HttpError> {
  catch(exception: HttpError, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    response.status(exception.statusCode).json({
      statusCode: exception.statusCode,
      message: exception.message,
    });
  }
}

Testing

Test

Utility for creating testing modules.

class Test {
  static createTestingModule(metadata: TestingModuleMetadata): TestingModuleBuilder
}

TestingModuleBuilder

class TestingModuleBuilder {
  overrideProvider(token: Type<unknown>): { useValue(value: unknown): TestingModuleBuilder }
  compile(): Promise<TestingModule>
}

TestingModule

class TestingModule {
  get<T>(token: Type<T>): T
}

Usage:

const module = await Test.createTestingModule({
  controllers: [UserController],
  providers: [UserService],
}).compile();

const controller = module.get(UserController);
const service = module.get(UserService);

Middleware

GlobalMiddlewareManager

Manages application-wide middleware.

class GlobalMiddlewareManager {
  use(middleware: MiddlewareClass): void
}

CorsMiddleware

class CorsMiddleware {
  constructor(options?: CorsOptions)
}

interface CorsOptions {
  origin?: string | string[];
  methods?: string[];
  allowedHeaders?: string[];
  credentials?: boolean;
}

LoggerMiddleware

Built-in request logging middleware.

class LoggerMiddleware { }

SecurityHeadersMiddleware

class SecurityHeadersMiddleware {
  constructor(options?: SecurityHeadersOptions)
}

RateLimitMiddleware

class RateLimitMiddleware {
  constructor(options?: RateLimitOptions)
}

interface RateLimitOptions {
  windowMs?: number;
  max?: number;
}

CsrfMiddleware

class CsrfMiddleware {
  constructor(options?: CsrfOptions)
}

TimeoutMiddleware

class TimeoutMiddleware {
  constructor(options?: TimeoutOptions)
}

interface TimeoutOptions {
  timeout?: number;
}

File Upload

@UploadedFile(fieldName)

Parameter decorator to extract a single uploaded file.

function UploadedFile(fieldName: string): ParameterDecorator

@UploadedFiles(fieldName)

Parameter decorator to extract multiple uploaded files.

function UploadedFiles(fieldName: string): ParameterDecorator

UploadedFileType

interface UploadedFile {
  filename: string;
  size: number;
  mimetype: string;
  buffer: Buffer;
}

Lifecycle Hooks

OnModuleInit

interface OnModuleInit {
  onModuleInit(): Promise<void>;
}

OnModuleDestroy

interface OnModuleDestroy {
  onModuleDestroy(): Promise<void>;
}

Usage:

@Service()
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
  async onModuleInit() {
    await this.connect();
  }

  async onModuleDestroy() {
    await this.disconnect();
  }
}

Shutdown & Health

ShutdownManager

class ShutdownManager {
  register(handler: ShutdownHandler): void
}

HealthCheckManager

class HealthCheckManager {
  register(check: HealthCheck): void
  runAll(): Promise<HealthCheckResult[]>
}

BuiltInHealthChecks

Pre-built health checks for common system metrics.

class BuiltInHealthChecks {
  static memoryCheck(): HealthCheck
  static eventLoopCheck(): HealthCheck
}

Security Utilities

Sanitization functions exported from @hazeljs/core:

function sanitizeHtml(input: string): string
function sanitizeString(input: string): string
function sanitizeUrl(input: string): string
function sanitizeEmail(input: string): string
function sanitizeSql(input: string): string
function sanitizeObject(input: Record<string, unknown>): Record<string, unknown>
function escapeHtml(input: string): string

Core Types

type Type<T = unknown> = new (...args: any[]) => T;

type InjectionToken<T = unknown> = string | symbol | Type<T>;

interface RequestContext {
  method: string;
  url: string;
  headers: Record<string, string>;
  params: Record<string, string>;
  query: Record<string, string>;
  body: unknown;
  dtoType?: Type<unknown>;
  user?: { id: number; username: string; role: string };
  req?: Request;
}