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>
}
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.
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) { }
@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) { }
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() { }
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[];
}
| Class | Alias | Status Code | Default Message |
|---|---|---|---|
BadRequestError | BadRequestException | 400 | — |
UnauthorizedError | UnauthorizedException | 401 | 'Unauthorized' |
ForbiddenError | ForbiddenException | 403 | 'Forbidden' |
NotFoundError | NotFoundException | 404 | 'Not Found' |
ConflictError | ConflictException | 409 | — |
InternalServerError | InternalServerErrorException | 500 | '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
}
Interceptors
Interceptor
Interface for creating custom interceptors.
abstract class Interceptor {
abstract intercept(context: RequestContext, next: () => Promise<unknown>): Promise<unknown>;
}
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;
};
}
Usage:
@Catch(HttpError)
export class HttpExceptionFilter 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:
@Injectable()
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[]>
}
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;
}