Grouped by type
Routing, lifecycle, DI, security, TypeORM, mailer, cache, scheduler, and queue decorators are separated so similar APIs stay together.
Decorators
This page lists the framework decorator surface exposed by the upstream packages, grouped by use case and labeled with the package each decorator comes from, plus small usage examples you can adapt directly.
116 decorators across 16 groups
Routing, lifecycle, DI, security, TypeORM, mailer, cache, scheduler, and queue decorators are separated so similar APIs stay together.
Every entry shows the package and upstream source path where the decorator lives.
Each decorator includes a short snippet drawn from the same patterns used in xtaskjs samples and this site.
Catalog
Decorator Group
Route declaration and request-pipeline decorators exported by @xtaskjs/common. These are the core HTTP building blocks used by controllers in every sample.
13 decorators
Decorator Group
Lifecycle decorators from @xtaskjs/common used to run startup logic, CLI tasks, and event handlers inside the application lifecycle.
3 decorators
Decorator Group
Dependency-injection and component decorators from @xtaskjs/core. These mark providers for container discovery and select named bindings for injection.
8 decorators
Decorator Group
Authentication, authorization, strategy, and injector decorators exported by @xtaskjs/security. These layer on top of @xtaskjs/common route metadata.
10 decorators
Decorator Group
TypeORM registration and injection decorators exported by @xtaskjs/typeorm. These bind datasources and repositories into the same DI container.
5 decorators
Decorator Group
CQRS configuration, handler, projection, idempotency, and injector decorators exported by @xtaskjs/cqrs. These connect command, query, and event flows to the xtaskjs container and read or write datasource aliases.
16 decorators
Decorator Group
Configuration, aggregate, subscriber, and injector decorators exported by @xtaskjs/event-source. These wire aggregate metadata, event appliers, repositories, and stored-event subscribers into the xtaskjs lifecycle.
9 decorators
Decorator Group
Mailer decorators exported by @xtaskjs/mailer. These register transports and templates and inject delivery services into DI-managed classes.
5 decorators
Decorator Group
Configuration and injector decorators exported by @xtaskjs/internationalization. These register locale behavior and expose translation services inside DI-managed classes.
7 decorators
Decorator Group
DTO-oriented decorators from @xtaskjs/value-objects that turn raw request fields into normalized domain wrappers before controllers and services consume them.
1 decorators
Decorator Group
Configuration, model, injector, and method decorators from @xtaskjs/cache used to register cache models, inject repositories or services, and control read/write cache behavior in DI-managed services.
9 decorators
Decorator Group
HTTP response decorators from @xtaskjs/cache used to apply Cache-Control directives, validators, and Vary behavior to routes, plus injector access to HttpCacheService.
7 decorators
Decorator Group
Scheduling decorators from @xtaskjs/scheduler used to declare cron, interval, and timeout jobs and to inject runtime scheduler services.
5 decorators
Decorator Group
Rate-limiting decorators from @xtaskjs/throttler used to protect routes and inject runtime throttling services.
3 decorators
Decorator Group
Gateway, event, and injector decorators exported by @xtaskjs/socket-io. These keep realtime handlers inside regular xtaskjs services and wire Socket.IO namespaces into the DI container.
8 decorators
Decorator Group
Queue consumer, publish, and injector decorators exported by @xtaskjs/queues. These wire broker transports and in-memory queues into DI-managed services.
7 decorators
Decorator Group
Route declaration and request-pipeline decorators exported by @xtaskjs/common. These are the core HTTP building blocks used by controllers in every sample.
Defines the base route path for an HTTP controller and can attach shared middlewares, guards, and pipes.
import { Controller, Get } from "@xtaskjs/common";
@Controller("/users")
export class UsersController {
@Get("/")
list() {
return [];
}
}
Registers a GET route handler and optionally adds route-specific middleware, guards, or pipes.
import { Controller, Get } from "@xtaskjs/common";
@Controller("/health")
export class HealthController {
@Get("/")
status() {
return { ok: true };
}
}
Registers a POST route handler for commands, form submissions, or resource creation.
import { Controller, Post } from "@xtaskjs/common";
@Controller("/users")
export class UsersController {
@Post("/")
create(req: any) {
return { email: req.body.email, created: true };
}
}
Registers a PATCH route handler for partial updates.
import { Controller, Patch } from "@xtaskjs/common";
@Controller("/users")
export class UsersController {
@Patch("/:id")
update(req: any) {
return { id: req.params.id, updated: true };
}
}
Registers a DELETE route handler for removals and destructive operations.
import { Controller, Delete } from "@xtaskjs/common";
@Controller("/users")
export class UsersController {
@Delete("/:id")
remove(req: any) {
return { id: req.params.id, removed: true };
}
}
Binds request body data to a controller parameter and supports DTO transformation when validation pipes are enabled.
import { Body, Controller, Post } from "@xtaskjs/common";
class CreateUserDto {
email!: string;
}
@Controller("/users")
export class UsersController {
@Post("/")
create(@Body() body: CreateUserDto) {
return body;
}
}
Extracts route parameters by name or as a full params object for typed handler input.
import { Controller, Get, Param } from "@xtaskjs/common";
@Controller("/users")
export class UsersController {
@Get("/:id")
detail(@Param("id") id: string) {
return { id };
}
}
Maps query-string values to a method parameter, optionally by property name.
import { Controller, Get, Query } from "@xtaskjs/common";
@Controller("/users")
export class UsersController {
@Get("/")
list(@Query("role") role?: string) {
return { role };
}
}
Injects the adapter request object into a controller handler parameter.
import { Controller, Get, Req } from "@xtaskjs/common";
@Controller("/auth")
export class AuthController {
@Get("/me")
me(@Req() req: any) {
return { auth: req.auth };
}
}
Injects the adapter response object into a controller handler parameter.
import { Controller, Get, Res } from "@xtaskjs/common";
@Controller("/health")
export class HealthController {
@Get("/")
status(@Res() res: any) {
return { statusCode: res.statusCode || 200 };
}
}
Adds one or more middlewares to a controller or route so cross-cutting logic runs before the handler.
import { Controller, Get, UseMiddlewares } from "@xtaskjs/common";
const requestLogger = async (_context: any, next: () => Promise<void>) => {
await next();
};
@Controller("/audit")
@UseMiddlewares(requestLogger)
export class AuditController {
@Get("/")
list() {
return { ok: true };
}
}
Attaches guard functions to a controller or route to allow, deny, or enrich request context before execution.
import { Controller, Get, UseGuards } from "@xtaskjs/common";
const adminGuard = (context: any) => context.request?.headers?.["x-role"] === "admin";
@Controller("/admin")
export class AdminController {
@Get("/")
@UseGuards(adminGuard)
dashboard() {
return { secure: true };
}
}
Applies argument transformation or validation functions before a route handler consumes input.
import { Controller, Post, UsePipes } from "@xtaskjs/common";
const trimEmailPipe = (value: any) => ({ ...value, email: String(value.email || "").trim() });
@Controller("/accounts")
export class AccountController {
@Post("/")
@UsePipes(trimEmailPipe)
create(req: any) {
return req.body;
}
}
Decorator Group
Lifecycle decorators from @xtaskjs/common used to run startup logic, CLI tasks, and event handlers inside the application lifecycle.
Registers a lifecycle event handler for a given phase and execution priority.
import { OnEvent } from "@xtaskjs/common";
export class AuditListener {
@OnEvent("AFTER_CONTROLLER_HANDLER", 10)
afterHandler() {
console.log("controller completed");
}
}
Runs a method during application startup with optional priority ordering.
import { ApplicationRunner } from "@xtaskjs/common";
import { Service } from "@xtaskjs/core";
@Service()
export class SeedRunner {
@ApplicationRunner(100)
async seed() {
console.log("seeding application data");
}
}
Marks a method as a command-line lifecycle runner so it can execute in CLI-oriented flows.
import { CommandLineRunner } from "@xtaskjs/common";
import { Service } from "@xtaskjs/core";
@Service()
export class ReportsRunner {
@CommandLineRunner(0)
async generate() {
console.log("generating reports");
}
}
Decorator Group
Dependency-injection and component decorators from @xtaskjs/core. These mark providers for container discovery and select named bindings for injection.
Low-level component decorator that stores DI metadata such as scope, condition, name, and primary selection.
import { Component } from "@xtaskjs/core";
@Component({ scope: "singleton", name: "clock" })
export class ClockService {}
Convenience stereotype for registering a class as a DI-managed service component.
import { Service } from "@xtaskjs/core";
@Service()
export class BillingService {}
Registers a class as a controller component in the DI container. This is separate from the HTTP route decorator exported by @xtaskjs/common.
import { Controller } from "@xtaskjs/core";
@Controller({ name: "admin-controller" })
export class AdminComponent {}
Convenience stereotype for repository-like providers managed by the DI container.
import { Repository } from "@xtaskjs/core";
@Repository()
export class UserLookupRepository {}
Injects a dependency into a property. The package also exports Autowired as an alias of AutoWired.
import { AutoWired } from "@xtaskjs/core";
import { UserService } from "./user.service";
export class AccountController {
@AutoWired({ qualifier: UserService.name })
private readonly users!: UserService;
}
Selects a named binding for constructor-parameter injection when multiple implementations share the same type.
import { Qualifier, Service } from "@xtaskjs/core";
@Service()
export class NotificationService {
constructor(@Qualifier("mailer:notifications") private readonly transport: any) {}
}
Marks a method to run after dependency injection completes for the instance.
import { PostConstruct, Service } from "@xtaskjs/core";
@Service()
export class BootstrapService {
@PostConstruct()
init() {
console.log("initialized");
}
}
Marks a method to run when the container destroys managed instances during shutdown.
import { PreDestroy, Service } from "@xtaskjs/core";
@Service()
export class WorkerService {
@PreDestroy()
stop() {
console.log("stopping");
}
}
Decorator Group
Authentication, authorization, strategy, and injector decorators exported by @xtaskjs/security. These layer on top of @xtaskjs/common route metadata.
Requires a successful authentication result before a controller or route executes. It can target a specific strategy or strategy list.
import { Controller, Get } from "@xtaskjs/common";
import { Authenticated } from "@xtaskjs/security";
@Controller("/me")
@Authenticated()
export class ProfileController {
@Get("/")
profile(req: any) {
return req.user;
}
}
Alias of Authenticated for projects that prefer a shorter decorator name.
import { Auth } from "@xtaskjs/security";
@Auth(["default", "encrypted"])
export class SecureAreaController {}
Applies role-based authorization requirements to an already authenticated route.
import { Controller, Get } from "@xtaskjs/common";
import { Authenticated, Roles } from "@xtaskjs/security";
@Controller("/admin")
@Authenticated()
export class AdminController {
@Get("/")
@Roles("admin")
dashboard() {
return { secure: true };
}
}
Marks a route as publicly accessible even when the surrounding controller is authenticated by default.
import { Controller, Get } from "@xtaskjs/common";
import { AllowAnonymous, Authenticated } from "@xtaskjs/security";
@Controller("/admin")
@Authenticated()
export class AdminController {
@Get("/health")
@AllowAnonymous()
health() {
return { ok: true };
}
}
Decorator form of registerJwtStrategy() for registering a JWT strategy definition during module loading.
import { JwtSecurityStrategy } from "@xtaskjs/security";
@JwtSecurityStrategy({
name: "default",
default: true,
secretOrKey: process.env.JWT_SECRET,
})
export class DefaultJwtStrategy {}
Decorator form of registerJweStrategy() for encrypted token flows.
import { JweSecurityStrategy } from "@xtaskjs/security";
@JweSecurityStrategy({
name: "encrypted",
decryptionKey: process.env.JWE_SECRET || "secret",
})
export class EncryptedStrategy {}
Injects the SecurityAuthenticationService registered by the security lifecycle manager.
import { Service } from "@xtaskjs/core";
import { InjectAuthenticationService, SecurityAuthenticationService } from "@xtaskjs/security";
@Service()
export class SessionAuditService {
constructor(
@InjectAuthenticationService()
private readonly authentication: SecurityAuthenticationService
) {}
}
Injects the SecurityAuthorizationService used for role and permission decisions.
import { Service } from "@xtaskjs/core";
import { InjectAuthorizationService, SecurityAuthorizationService } from "@xtaskjs/security";
@Service()
export class PolicyService {
constructor(
@InjectAuthorizationService()
private readonly authorization: SecurityAuthorizationService
) {}
}
Injects the configured Passport instance managed by xtaskjs security.
import { Service } from "@xtaskjs/core";
import { InjectPassport } from "@xtaskjs/security";
@Service()
export class PassportInspector {
constructor(@InjectPassport() private readonly passport: any) {}
}
Injects the SecurityLifecycleManager so advanced services can inspect strategies or authentication state wiring.
import { Service } from "@xtaskjs/core";
import { InjectSecurityLifecycleManager } from "@xtaskjs/security";
@Service()
export class SecurityDiagnosticsService {
constructor(@InjectSecurityLifecycleManager() private readonly lifecycle: any) {}
}
Decorator Group
TypeORM registration and injection decorators exported by @xtaskjs/typeorm. These bind datasources and repositories into the same DI container.
Registers a TypeORM datasource definition for xtask startup and shutdown management.
import { TypeOrmDataSource } from "@xtaskjs/typeorm";
import { UserEntity } from "./user.entity";
@TypeOrmDataSource({
name: "default",
type: "sqlite",
database: "app.sqlite",
entities: [UserEntity],
synchronize: true,
})
export class DatabaseConfig {}
Injects a named datasource instance managed by xtaskjs TypeORM integration.
import { Service } from "@xtaskjs/core";
import { DataSource, InjectDataSource } from "@xtaskjs/typeorm";
@Service()
export class HealthQueryService {
constructor(@InjectDataSource() private readonly dataSource: DataSource) {}
}
Injects a TypeORM repository for a given entity and datasource name.
import { Service } from "@xtaskjs/core";
import { InjectRepository, Repository } from "@xtaskjs/typeorm";
import { UserEntity } from "./user.entity";
@Service()
export class UsersService {
constructor(
@InjectRepository(UserEntity)
private readonly users: Repository<UserEntity>
) {}
}
Registers a migration class in the TypeORM migration registry for a named datasource.
import { MigrationInterface, QueryRunner, TypeOrmMigration } from "@xtaskjs/typeorm";
@TypeOrmMigration({ dataSourceName: "default" })
export class CreateAuditEntries1700000000000 implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query("CREATE TABLE audit_entries (id integer primary key autoincrement, message varchar(120) not null)");
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query("DROP TABLE audit_entries");
}
}
Registers an ordered seeder class that runs after datasource initialization when seeders are enabled.
import { DataSource, TypeOrmSeeder } from "@xtaskjs/typeorm";
@TypeOrmSeeder({ dataSourceName: "default", order: 1 })
export class AuditEntriesSeeder {
async run(dataSource: DataSource): Promise<void> {
await dataSource.query("INSERT INTO audit_entries (message) VALUES ('seeded')");
}
}
Decorator Group
CQRS configuration, handler, projection, idempotency, and injector decorators exported by @xtaskjs/cqrs. These connect command, query, and event flows to the xtaskjs container and read or write datasource aliases.
Decorator form of configureCqrs() for binding the read and write datasource aliases and optional idempotency store during module loading.
import { Cqrs } from "@xtaskjs/cqrs";
@Cqrs({ writeDataSourceName: "write-db", readDataSourceName: "read-db" })
export class CqrsConfiguration {}
Registers a DI-managed class as the single handler for a command message type.
import { Service } from "@xtaskjs/core";
import { CommandHandler, ICommandHandler } from "@xtaskjs/cqrs";
class CreateUserCommand {
constructor(public readonly name: string) {}
}
@Service()
@CommandHandler(CreateUserCommand)
export class CreateUserHandler implements ICommandHandler<CreateUserCommand, string> {
execute(command: CreateUserCommand) {
return command.name;
}
}
Registers a DI-managed class as the handler for a query message type.
import { Service } from "@xtaskjs/core";
import { IQueryHandler, QueryHandler } from "@xtaskjs/cqrs";
class ListUsersQuery {}
@Service()
@QueryHandler(ListUsersQuery)
export class ListUsersHandler implements IQueryHandler<ListUsersQuery, string[]> {
execute() {
return ["Ada"];
}
}
Registers one or more event handlers that react after a message publishes an event on the CQRS event bus.
import { Service } from "@xtaskjs/core";
import { EventHandler, IEventHandler } from "@xtaskjs/cqrs";
class UserCreatedEvent {
constructor(public readonly id: string) {}
}
@Service()
@EventHandler(UserCreatedEvent)
export class UserProjectionHandler implements IEventHandler<UserCreatedEvent> {
async handle(event: UserCreatedEvent) {
console.log(event.id);
}
}
Registers an orchestration component that reacts to events with access to command, query, and event buses. Saga is an alias of ProcessManager.
import { Service } from "@xtaskjs/core";
import { IProcessManager, ProcessManager, ProcessManagerContext } from "@xtaskjs/cqrs";
class UserCreatedEvent {
constructor(public readonly id: string) {}
}
@Service()
@ProcessManager(UserCreatedEvent)
export class WelcomeProcessManager implements IProcessManager<UserCreatedEvent> {
async handle(event: UserCreatedEvent, context: ProcessManagerContext) {
await context.commandBus.execute({ userId: event.id });
}
}
Registers a named projection rebuilder so operators or diagnostics flows can rebuild a read model from write-side state.
import { Service } from "@xtaskjs/core";
import { IProjectionRebuilder, ProjectionRebuilder } from "@xtaskjs/cqrs";
@Service()
@ProjectionRebuilder("users")
export class UserProjectionRebuilder implements IProjectionRebuilder {
async rebuild() {
console.log("rebuild read model");
}
}
Adds idempotency metadata to a command handler so repeated executions can reuse a cached result instead of running the write-side action again.
import { CommandHandler, IdempotentCommand } from "@xtaskjs/cqrs";
class CreateUserCommand {
constructor(public readonly name: string, public readonly idempotencyKey: string) {}
}
@IdempotentCommand<CreateUserCommand>({ key: (command) => command.idempotencyKey })
@CommandHandler(CreateUserCommand)
export class CreateUserHandler {
execute(command: CreateUserCommand) {
return `${command.name}:${command.idempotencyKey}`;
}
}
Injects CommandBus so controllers or services can dispatch commands without reaching into the lifecycle manager directly.
import { Service } from "@xtaskjs/core";
import { CommandBus, InjectCommandBus } from "@xtaskjs/cqrs";
@Service()
export class UsersFacade {
constructor(@InjectCommandBus() private readonly commandBus: CommandBus) {}
}
Injects QueryBus so read-side requests can be dispatched from controllers, presenters, or services.
import { Service } from "@xtaskjs/core";
import { InjectQueryBus, QueryBus } from "@xtaskjs/cqrs";
@Service()
export class ReportsFacade {
constructor(@InjectQueryBus() private readonly queryBus: QueryBus) {}
}
Injects EventBus so handlers can publish follow-up domain or integration events after write-side work completes.
import { Service } from "@xtaskjs/core";
import { EventBus, InjectEventBus } from "@xtaskjs/cqrs";
@Service()
export class UserEventsPublisher {
constructor(@InjectEventBus() private readonly events: EventBus) {}
}
Injects the configured idempotency store implementation used by idempotent command handlers.
import { InjectIdempotencyStore, IIdempotencyStore } from "@xtaskjs/cqrs";
import { Service } from "@xtaskjs/core";
@Service()
export class IdempotencyDiagnosticsService {
constructor(@InjectIdempotencyStore() private readonly store: IIdempotencyStore) {}
}
Injects the configured read-side datasource alias managed by CQRS and backed by @xtaskjs/typeorm.
import { Service } from "@xtaskjs/core";
import { InjectReadDataSource } from "@xtaskjs/cqrs";
import { DataSource } from "@xtaskjs/typeorm";
@Service()
export class ReadDiagnosticsService {
constructor(@InjectReadDataSource() private readonly readDataSource: DataSource) {}
}
Injects the configured write-side datasource alias for command handlers or projection rebuilders that need direct datasource access.
import { Service } from "@xtaskjs/core";
import { InjectWriteDataSource } from "@xtaskjs/cqrs";
import { DataSource } from "@xtaskjs/typeorm";
@Service()
export class WriteDiagnosticsService {
constructor(@InjectWriteDataSource() private readonly writeDataSource: DataSource) {}
}
Injects a repository from the configured read-side datasource alias so queries can stay projection-focused.
import { Service } from "@xtaskjs/core";
import { InjectReadRepository } from "@xtaskjs/cqrs";
import { Repository } from "@xtaskjs/typeorm";
class UserProjection {}
@Service()
export class UsersReadService {
constructor(@InjectReadRepository(UserProjection) private readonly users: Repository<UserProjection>) {}
}
Injects a repository from the configured write-side datasource alias for command handlers and write-model maintenance flows.
import { Service } from "@xtaskjs/core";
import { InjectWriteRepository } from "@xtaskjs/cqrs";
import { Repository } from "@xtaskjs/typeorm";
class UserEntity {}
@Service()
export class UsersWriteService {
constructor(@InjectWriteRepository(UserEntity) private readonly users: Repository<UserEntity>) {}
}
Injects the CqrsLifecycleManager for advanced diagnostics, projection rebuild operations, and direct runtime inspection.
import { Service } from "@xtaskjs/core";
import { InjectCqrsLifecycleManager } from "@xtaskjs/cqrs";
@Service()
export class CqrsDiagnosticsService {
constructor(@InjectCqrsLifecycleManager() private readonly lifecycle: any) {}
}
Decorator Group
Configuration, aggregate, subscriber, and injector decorators exported by @xtaskjs/event-source. These wire aggregate metadata, event appliers, repositories, and stored-event subscribers into the xtaskjs lifecycle.
Decorator form of configureEventSource() for registering the event store, publisher, and optional runtime flags during module loading.
import { EventSource, createTypeOrmEventStore } from "@xtaskjs/event-source";
@EventSource({
store: createTypeOrmEventStore({ dataSourceName: "write-db", tableName: "event_store" }),
})
export class EventSourceConfiguration {}
Registers aggregate metadata such as the aggregate name and stream key so repositories can load and persist event streams consistently.
import { EventSourcedAggregate, EventSourcedAggregateRoot } from "@xtaskjs/event-source";
@EventSourcedAggregate({ stream: "users" })
export class UserAggregate extends EventSourcedAggregateRoot {}
Registers the method that mutates aggregate state for a given event type during both live execution and historical replay.
import { ApplyEvent } from "@xtaskjs/event-source";
class UserRegisteredEvent {
constructor(public readonly email: string) {}
}
export class UserAggregate {
public email?: string;
@ApplyEvent(UserRegisteredEvent)
onRegistered(event: UserRegisteredEvent) {
this.email = event.email;
}
}
Registers a DI-managed subscriber that reacts after stored events are appended, making it suitable for projections, integrations, and side effects.
import { Service } from "@xtaskjs/core";
import { EventSourceSubscriber, IEventSourceSubscriber } from "@xtaskjs/event-source";
class UserRegisteredEvent {
constructor(public readonly email: string) {}
}
@Service()
@EventSourceSubscriber(UserRegisteredEvent)
export class WelcomeProjection implements IEventSourceSubscriber<UserRegisteredEvent> {
handle(event: UserRegisteredEvent) {
console.log(event.email);
}
}
Injects the repository for a specific event-sourced aggregate so services can create, load, and save streams through the lifecycle-managed store.
import { Service } from "@xtaskjs/core";
import { EventSourceRepository, InjectEventSourceRepository } from "@xtaskjs/event-source";
class UserAggregate {}
@Service()
export class UserService {
constructor(
@InjectEventSourceRepository(UserAggregate)
private readonly users: EventSourceRepository<any>
) {}
}
Injects the active event store implementation when advanced services need direct stream append or load access.
import { Service } from "@xtaskjs/core";
import { InjectEventStore } from "@xtaskjs/event-source";
@Service()
export class EventStoreDiagnosticsService {
constructor(@InjectEventStore() private readonly store: any) {}
}
Injects the in-process stored-event bus so services can publish persisted envelopes to local subscribers when they need low-level runtime control.
import { Service } from "@xtaskjs/core";
import { InjectEventSourceBus } from "@xtaskjs/event-source";
@Service()
export class EventReplayService {
constructor(@InjectEventSourceBus() private readonly bus: any) {}
}
Injects the configured external event publisher so services can inspect or extend publication behavior beyond the default queue bridge.
import { Service } from "@xtaskjs/core";
import { InjectEventPublisher } from "@xtaskjs/event-source";
@Service()
export class EventPublisherDiagnosticsService {
constructor(@InjectEventPublisher() private readonly publisher: any) {}
}
Injects the EventSourceLifecycleManager for repository lookup, initialization checks, subscriber inspection, and lower-level event-source runtime access.
import { Service } from "@xtaskjs/core";
import { InjectEventSourceLifecycleManager } from "@xtaskjs/event-source";
@Service()
export class EventSourceDiagnosticsService {
constructor(@InjectEventSourceLifecycleManager() private readonly lifecycle: any) {}
}
Decorator Group
Mailer decorators exported by @xtaskjs/mailer. These register transports and templates and inject delivery services into DI-managed classes.
Decorator form of registerMailerTransport() for registering a named mail transport during module loading.
import { MailerTransport, createMailtrapTransportOptions } from "@xtaskjs/mailer";
const transport = process.env.MAIL_TRANSPORT_PROVIDER === "smtp"
? {
host: process.env.MAIL_SMTP_HOST || "smtp.example.com",
port: Number(process.env.MAIL_SMTP_PORT || 587),
secure: process.env.MAIL_SMTP_SECURE === "true",
auth: {
user: process.env.MAIL_SMTP_USER || "user",
pass: process.env.MAIL_SMTP_PASS || "pass",
},
}
: createMailtrapTransportOptions({
username: process.env.MAILTRAP_SMTP_USER || "user",
password: process.env.MAILTRAP_SMTP_PASS || "pass",
host: process.env.MAILTRAP_SMTP_HOST || "sandbox.smtp.mailtrap.io",
port: Number(process.env.MAILTRAP_SMTP_PORT || 2525),
secure: process.env.MAILTRAP_SMTP_SECURE === "true",
});
@MailerTransport({
name: "default",
defaults: { from: "hello@xtaskjs.dev" },
transport,
})
export class DefaultTransportRegistration {}
Decorator form of registerMailerTemplate() for reusable inline or file-rendered email templates.
import { MailerTemplate } from "@xtaskjs/mailer";
@MailerTemplate({
name: "welcome",
subject: "Welcome {{user.name}}",
text: "Hello {{user.name}}",
html: "<h1>Hello {{user.name}}</h1>",
})
export class WelcomeTemplateRegistration {}
Injects MailerService so a DI-managed service can render templates and send mail.
import { Service } from "@xtaskjs/core";
import { InjectMailerService, MailerService } from "@xtaskjs/mailer";
@Service()
export class EmailService {
constructor(@InjectMailerService() private readonly mailer: MailerService) {}
}
Injects a named transport so a service can send directly on a specific channel such as notifications.
import { Service } from "@xtaskjs/core";
import { InjectMailerTransport, MailerTransporter } from "@xtaskjs/mailer";
@Service()
export class AlertsService {
constructor(
@InjectMailerTransport("notifications")
private readonly notifications: MailerTransporter
) {}
}
Injects the MailerLifecycleManager for advanced inspection, verification, or transporter lookup.
import { Service } from "@xtaskjs/core";
import { InjectMailerLifecycleManager } from "@xtaskjs/mailer";
@Service()
export class MailDiagnosticsService {
constructor(@InjectMailerLifecycleManager() private readonly lifecycle: any) {}
}
Decorator Group
Configuration and injector decorators exported by @xtaskjs/internationalization. These register locale behavior and expose translation services inside DI-managed classes.
Decorator form of configureInternationalization() for registering default locale, fallback locale, currency, and timezone settings during module loading.
import { Internationalization } from "@xtaskjs/internationalization";
@Internationalization({
defaultLocale: "en-US",
fallbackLocale: "en-US",
defaultCurrency: "USD",
defaultTimeZone: "UTC",
})
export class AppI18nConfiguration {}
Registers a locale definition with translations, locale-specific currency and timezone values, and optional namespace dictionaries.
import { InternationalizationLocale } from "@xtaskjs/internationalization";
@InternationalizationLocale({
locale: "es-ES",
currency: "EUR",
timeZone: "Europe/Madrid",
translations: { home: { title: "Bienvenida" } },
})
export class SpanishLocaleRegistration {}
Registers a custom locale resolver that can derive locale context from the request, headers, container state, or tenant metadata.
import { InternationalizationResolver } from "@xtaskjs/internationalization";
@InternationalizationResolver(({ request }) => {
return request?.headers?.["x-locale"] || request?.query?.locale;
})
export class HeaderLocaleResolver {}
Injects InternationalizationService so controllers and services can translate keys, format values, inspect locales, and load namespaces on demand.
import { Service } from "@xtaskjs/core";
import { InjectInternationalizationService, InternationalizationService } from "@xtaskjs/internationalization";
@Service()
export class CheckoutPresenter {
constructor(
@InjectInternationalizationService()
private readonly intl: InternationalizationService
) {}
}
Alias of InjectInternationalizationService for shorter injection syntax in services and controllers.
import { InjectI18nService, InternationalizationService } from "@xtaskjs/internationalization";
import { Service } from "@xtaskjs/core";
@Service()
export class AliasI18nService {
constructor(@InjectI18nService() private readonly intl: InternationalizationService) {}
}
Injects the InternationalizationLifecycleManager for advanced inspection of loaded locales, namespaces, request context, or formatter registration.
import { Service } from "@xtaskjs/core";
import { InjectInternationalizationLifecycleManager } from "@xtaskjs/internationalization";
@Service()
export class LocaleDiagnosticsService {
constructor(
@InjectInternationalizationLifecycleManager()
private readonly lifecycle: any
) {}
}
Alias of InjectInternationalizationLifecycleManager for compact naming in diagnostics and infrastructure services.
import { InjectI18nLifecycleManager } from "@xtaskjs/internationalization";
import { Service } from "@xtaskjs/core";
@Service()
export class AliasLifecycleService {
constructor(@InjectI18nLifecycleManager() private readonly lifecycle: any) {}
}
Decorator Group
DTO-oriented decorators from @xtaskjs/value-objects that turn raw request fields into normalized domain wrappers before controllers and services consume them.
Transforms raw DTO input into a value object instance during class-transformer conversion so downstream code receives a validated wrapper instead of a primitive.
import { plainToInstance } from "class-transformer";
import { StringValueObject, TransformValueObject } from "@xtaskjs/value-objects";
class EmailAddress extends StringValueObject {
constructor(value: string) {
super(value.trim().toLowerCase());
}
}
class CreateUserDto {
@TransformValueObject(EmailAddress)
email!: EmailAddress;
}
const dto = plainToInstance(CreateUserDto, { email: " USER@Example.com " });
Decorator Group
Configuration, model, injector, and method decorators from @xtaskjs/cache used to register cache models, inject repositories or services, and control read/write cache behavior in DI-managed services.
Decorator form of configureCache() for setting package-wide defaults such as driver, TTL, namespace, Redis options, and HTTP cache defaults while modules load.
import { CacheSettings } from "@xtaskjs/cache";
@CacheSettings({
defaultDriver: "memory",
defaultTtl: "30s",
namespace: "catalog",
})
export class CacheConfiguration {}
Registers a named cache model with driver selection, TTL defaults, serialization hooks, and optional Redis-specific overrides.
import { CacheModel } from "@xtaskjs/cache";
@CacheModel({ name: "products", ttl: "5m", driver: "redis" })
export class ProductCacheModel {}
Injects CacheService for model-level operations such as listModels(), get(), set(), remember(), delete(), and clear().
import { Service } from "@xtaskjs/core";
import { CacheService, InjectCacheService } from "@xtaskjs/cache";
@Service()
export class CacheInspectorService {
constructor(
@InjectCacheService()
private readonly cache: CacheService
) {}
}
Injects a model-scoped CacheRepository<T> so services can work directly with entries, hit metadata, and per-model TTL behavior.
import { Service } from "@xtaskjs/core";
import { CacheRepository, InjectCacheRepository } from "@xtaskjs/cache";
import { ProductCacheModel } from "./product-cache.model";
@Service()
export class ProductCacheReader {
constructor(
@InjectCacheRepository(ProductCacheModel)
private readonly products: CacheRepository<any>
) {}
}
Injects the lower-level cache lifecycle manager for diagnostics, initialization checks, repository resolution, and runtime state access.
import { Service } from "@xtaskjs/core";
import { InjectCacheLifecycleManager } from "@xtaskjs/cache";
@Service()
export class CacheLifecycleDiagnosticsService {
constructor(
@InjectCacheLifecycleManager()
private readonly lifecycle: any
) {}
}
Injects CacheAdminService for runtime inspection of models, entries, and effective HTTP cache metadata resolved from decorated routes.
import { Service } from "@xtaskjs/core";
import { CacheAdminService, InjectCacheAdminService } from "@xtaskjs/cache";
@Service()
export class CacheAdminInspector {
constructor(
@InjectCacheAdminService()
private readonly cacheAdmin: CacheAdminService
) {}
}
Reads through the configured repository. Cache hits skip method execution, while misses store the resolved result using an optional key builder, TTL override, and unless condition.
import { Service } from "@xtaskjs/core";
import { Cacheable } from "@xtaskjs/cache";
import { ProductCacheModel } from "./product-cache.model";
@Service()
export class ProductService {
@Cacheable({ model: ProductCacheModel, key: (id: string) => id, ttl: "15m" })
async getProduct(id: string) {
return { id, generatedAt: new Date().toISOString() };
}
}
Always runs the method and then writes the returned value into the cache, optionally guarding the write with when and overriding the stored TTL.
import { Service } from "@xtaskjs/core";
import { CachePut } from "@xtaskjs/cache";
import { ProductCacheModel } from "./product-cache.model";
@Service()
export class ProductRefreshService {
@CachePut({ model: ProductCacheModel, key: (id: string) => id })
async refreshProduct(id: string) {
return { id, refreshedAt: new Date().toISOString() };
}
}
Removes one cached entry or clears an entire model before or after the wrapped method runs, with optional key resolution and conditional execution.
import { Service } from "@xtaskjs/core";
import { CacheEvict } from "@xtaskjs/cache";
import { ProductCacheModel } from "./product-cache.model";
@Service()
export class ProductInvalidationService {
@CacheEvict({ model: ProductCacheModel, key: (id: string) => id })
async evictProduct(id: string) {
return true;
}
}
Decorator Group
HTTP response decorators from @xtaskjs/cache used to apply Cache-Control directives, validators, and Vary behavior to routes, plus injector access to HttpCacheService.
Injects HttpCacheService so services or controllers can build cache headers manually, inspect policy normalization, or describe effective route behavior.
import { Service } from "@xtaskjs/core";
import { HttpCacheService, InjectHttpCacheService } from "@xtaskjs/cache";
@Service()
export class CacheHeaderService {
constructor(
@InjectHttpCacheService()
private readonly httpCache: HttpCacheService
) {}
}
Applies a full HTTP cache policy to responses, including visibility, max-age, stale directives, ETag, Last-Modified, Expires, Vary, and conditional application rules.
import { Controller, Get } from "@xtaskjs/common";
import { CacheResponse } from "@xtaskjs/cache";
@Controller("/reports")
export class ReportsController {
@CacheResponse({ visibility: "private", maxAge: "60s", mustRevalidate: true })
@Get("/summary")
summary() {
return { ok: true };
}
}
Alias names for CacheResponse() when the intent is browser-facing cache headers rather than a generic response policy decorator.
import { Controller, Get } from "@xtaskjs/common";
import { BrowserCache } from "@xtaskjs/cache";
@Controller("/articles")
export class ArticleController {
@BrowserCache({ maxAge: "1m", staleWhileRevalidate: "30s" })
@Get("/:slug")
show() {
return { published: true };
}
}
Applies the same HTTP cache policy surface as CacheResponse(), but only when the decorated route returns view(...).
import { Controller, Get } from "@xtaskjs/common";
import { view } from "@xtaskjs/core";
import { CacheView } from "@xtaskjs/cache";
@Controller("/")
export class WebController {
@CacheView({ maxAge: "10m", etag: true })
@Get("/")
home() {
return view("home", { title: "Welcome" });
}
}
Disables browser storage for sensitive responses by combining no-store, no-cache, must-revalidate, and an already-expired Expires value.
import { Controller, Get } from "@xtaskjs/common";
import { NoStore } from "@xtaskjs/cache";
@Controller("/drafts")
export class DraftController {
@NoStore()
@Get("/preview")
preview() {
return { draft: true };
}
}
Forces revalidation by emitting no-cache and must-revalidate semantics while still allowing conditional requests when other validators are enabled.
import { Controller, Get } from "@xtaskjs/common";
import { NoCache } from "@xtaskjs/cache";
@Controller("/profile")
export class ProfileController {
@NoCache()
@Get("/")
show() {
return { profile: true };
}
}
Appends Vary header values so downstream caches distinguish responses by headers such as Accept-Language or Authorization.
import { Controller, Get } from "@xtaskjs/common";
import { BrowserCache, VaryBy } from "@xtaskjs/cache";
@Controller("/catalog")
export class CatalogController {
@BrowserCache({ maxAge: "2m" })
@VaryBy("accept-language", "authorization")
@Get("/")
list() {
return { ok: true };
}
}
Decorator Group
Scheduling decorators from @xtaskjs/scheduler used to declare cron, interval, and timeout jobs and to inject runtime scheduler services.
Registers a cron-based recurring job with optional groups, retries, timezone overrides, and boot execution behavior.
import { Service } from "@xtaskjs/core";
import { Cron } from "@xtaskjs/scheduler";
@Service()
export class ReportsScheduler {
@Cron("0 */5 * * * *", { name: "reports.flush", group: ["reports", "nightly"] })
flushReports() {
console.log("flush pending reports");
}
}
Registers a fixed-interval recurring job. Interval is an alias of Every for projects that prefer the more explicit name.
import { Service } from "@xtaskjs/core";
import { Every } from "@xtaskjs/scheduler";
@Service()
export class CacheScheduler {
@Every("10m", { name: "cache.compact", runOnInit: true })
compact() {
console.log("compact cache");
}
}
Registers a one-shot delayed task that runs after startup instead of on a recurring cadence.
import { Service } from "@xtaskjs/core";
import { Timeout } from "@xtaskjs/scheduler";
@Service()
export class WarmupScheduler {
@Timeout("30s", { name: "cache.warmup" })
warmup() {
console.log("warm cache once after startup");
}
}
Injects SchedulerService so services or controllers can inspect jobs and trigger groups or individual jobs manually.
import { Service } from "@xtaskjs/core";
import { InjectSchedulerService, SchedulerService } from "@xtaskjs/scheduler";
@Service()
export class SchedulerInspector {
constructor(
@InjectSchedulerService()
private readonly scheduler: SchedulerService
) {}
}
Injects the SchedulerLifecycleManager for lower-level control over startup state, active handles, and discovered job metadata.
import { Service } from "@xtaskjs/core";
import { InjectSchedulerLifecycleManager } from "@xtaskjs/scheduler";
@Service()
export class SchedulerDiagnosticsService {
constructor(
@InjectSchedulerLifecycleManager()
private readonly lifecycle: any
) {}
}
Decorator Group
Rate-limiting decorators from @xtaskjs/throttler used to protect routes and inject runtime throttling services.
Applies request throttling with a limit and TTL window, integrating with guard execution for protected endpoints.
import { Controller, Get } from "@xtaskjs/common";
import { Throttle } from "@xtaskjs/throttler";
@Controller("/auth")
export class AuthController {
@Get("/login")
@Throttle(10, "1m")
login() {
return { ok: true };
}
}
Injects ThrottlerService for runtime inspection and programmatic throttling operations.
import { Service } from "@xtaskjs/core";
import { InjectThrottlerService } from "@xtaskjs/throttler";
@Service()
export class ThrottlerDiagnosticsService {
constructor(@InjectThrottlerService() private readonly throttler: any) {}
}
Injects the throttler lifecycle manager for advanced diagnostics and low-level store integration checks.
import { Service } from "@xtaskjs/core";
import { InjectThrottlerLifecycleManager } from "@xtaskjs/throttler";
@Service()
export class ThrottlerLifecycleService {
constructor(@InjectThrottlerLifecycleManager() private readonly lifecycle: any) {}
}
Decorator Group
Gateway, event, and injector decorators exported by @xtaskjs/socket-io. These keep realtime handlers inside regular xtaskjs services and wire Socket.IO namespaces into the DI container.
Marks a DI-managed service as a realtime gateway, assigning namespace, optional name, groups, and disabled state for lifecycle discovery.
import { Service } from "@xtaskjs/core";
import { SocketGateway } from "@xtaskjs/socket-io";
@Service()
@SocketGateway({ namespace: "/chat", group: ["realtime", "chat"] })
export class ChatGateway {}
Runs when a client connects to the gateway namespace and receives the connected socket plus handler context.
import { Service } from "@xtaskjs/core";
import { OnSocketConnection, SocketGateway } from "@xtaskjs/socket-io";
@Service()
@SocketGateway({ namespace: "/chat" })
export class PresenceGateway {
@OnSocketConnection()
onConnect(socket: any, context: { namespace: any }) {
context.namespace.emit("presence.updated", { socketId: socket.id });
}
}
Runs when Socket.IO disconnects a client, making it a good place to update presence, release room state, or log disconnect reasons.
import { Service } from "@xtaskjs/core";
import { OnSocketDisconnect, SocketGateway } from "@xtaskjs/socket-io";
@Service()
@SocketGateway({ namespace: "/chat" })
export class PresenceGateway {
@OnSocketDisconnect()
onDisconnect(reason: string, socket: any) {
console.log(`socket ${socket.id} disconnected: ${reason}`);
}
}
Registers a named Socket.IO event handler, optionally overrides namespace or handler options, and automatically acknowledges returned values when the client expects an ack.
import { Service } from "@xtaskjs/core";
import { OnSocketEvent, SocketGateway } from "@xtaskjs/socket-io";
@Service()
@SocketGateway({ namespace: "/chat" })
export class ChatGateway {
@OnSocketEvent("chat.message")
onMessage(payload: { text: string }, context: { socket: any }) {
return { ok: true, socketId: context.socket.id, text: payload.text };
}
}
Injects SocketIoService so controllers and services can emit events, inspect namespaces, and list discovered gateways.
import { Service } from "@xtaskjs/core";
import { InjectSocketService, SocketIoService } from "@xtaskjs/socket-io";
@Service()
export class AnnouncementService {
constructor(
@InjectSocketService()
private readonly sockets: SocketIoService
) {}
}
Injects the SocketIoLifecycleManager for lower-level diagnostics, gateway inspection, namespace access, or manual emit control.
import { Service } from "@xtaskjs/core";
import { InjectSocketLifecycleManager } from "@xtaskjs/socket-io";
@Service()
export class SocketDiagnosticsService {
constructor(
@InjectSocketLifecycleManager()
private readonly lifecycle: any
) {}
}
Injects the root Socket.IO server instance when low-level adapter APIs or global broadcasts are required.
import { Service } from "@xtaskjs/core";
import { InjectSocketServer } from "@xtaskjs/socket-io";
@Service()
export class SocketServerBridge {
constructor(
@InjectSocketServer()
private readonly server: any
) {}
}
Injects one namespace instance by name so services can target a specific room topology without routing every emit through the root server.
import { Service } from "@xtaskjs/core";
import { InjectSocketNamespace } from "@xtaskjs/socket-io";
@Service()
export class ChatNamespacePublisher {
constructor(
@InjectSocketNamespace("/chat")
private readonly namespace: any
) {}
}
Decorator Group
Queue consumer, publish, and injector decorators exported by @xtaskjs/queues. These wire broker transports and in-memory queues into DI-managed services.
Registers a named queue consumer for a concrete queue and supports retries, groups, dead-letter routing, and transport selection.
import { Service } from "@xtaskjs/core";
import { QueueHandler } from "@xtaskjs/queues";
@Service()
export class OrdersConsumer {
@QueueHandler("orders.created", {
name: "orders.created.consumer",
transportName: "memory",
maxRetries: 3,
deadLetterQueue: "orders.dead",
})
async onOrderCreated(payload: { orderId: string }) {
console.log("created", payload.orderId);
}
}
Registers a topic or pattern-based listener that can subscribe to wildcards or broker topic filters depending on the transport.
import { Service } from "@xtaskjs/core";
import { QueuePattern } from "@xtaskjs/queues";
@Service()
export class AuditConsumer {
@QueuePattern("orders.*", {
name: "orders.audit",
transportName: "rabbitmq",
})
onOrderEvent(payload: any, context: { queue: string }) {
console.log(context.queue, payload);
}
}
Alias of QueueHandler for queue-specific consumers when teams prefer a subscribe-oriented naming style.
import { QueueSubscribe } from "@xtaskjs/queues";
import { Service } from "@xtaskjs/core";
@Service()
export class BillingConsumer {
@QueueSubscribe("billing.invoice.created")
onInvoice(payload: { invoiceId: string }) {
return payload.invoiceId;
}
}
Publishes the resolved method result to a queue after the method completes while preserving the original return value.
import { Service } from "@xtaskjs/core";
import { PublishToQueue } from "@xtaskjs/queues";
@Service()
export class CheckoutService {
@PublishToQueue("checkout.completed", { transportName: "memory" })
complete(orderId: string) {
return { orderId, status: "completed" };
}
}
Injects QueueService so services or controllers can publish messages, create producers, and inspect runtime consumers and transports.
import { Service } from "@xtaskjs/core";
import { InjectQueueService, QueueService } from "@xtaskjs/queues";
@Service()
export class QueuePublisher {
constructor(
@InjectQueueService()
private readonly queues: QueueService
) {}
}
Injects QueueLifecycleManager for advanced consumer, transport, and startup diagnostics.
import { InjectQueueLifecycleManager } from "@xtaskjs/queues";
import { Service } from "@xtaskjs/core";
@Service()
export class QueueLifecycleDiagnostics {
constructor(@InjectQueueLifecycleManager() private readonly lifecycle: any) {}
}
Injects a named QueueTransport implementation when low-level broker publish or subscription control is required.
import { Service } from "@xtaskjs/core";
import { InjectQueueTransport } from "@xtaskjs/queues";
@Service()
export class QueueTransportDiagnostics {
constructor(
@InjectQueueTransport("rabbitmq")
private readonly transport: any
) {}
}