API ReferenceDI & Decorators
DI & Decorators
Dependency injection and decorator-based metadata for structured applications.
NextRush provides a dependency injection system and decorator-based metadata for building structured, testable applications.
Package Overview
Loading diagram...
| Package | Purpose |
|---|---|
| @nextrush/di | Dependency injection container |
| @nextrush/decorators | Controller and route decorators |
How They Work Together
The DI system and decorators are designed to work together:
- @Service / @Repository — Mark classes for DI registration
- @Controller — Mark classes as HTTP controllers
- @Get / @Post — Define route handlers
- @Body / @Param — Extract request data
- Container — Resolve dependencies automatically
Quick Example
import { createApp, createRouter, listen } from 'nextrush';
import { controllersPlugin, Service, Controller, Get, Post, Body, Param } from 'nextrush/class';
// Service with DI
@Service()
class UserService {
private users = [{ id: '1', name: 'Alice' }];
findAll() {
return this.users;
}
create(data: { name: string }) {
const user = { id: Date.now().toString(), ...data };
this.users.push(user);
return user;
}
}
// Controller with injected service
@Controller('/users')
class UserController {
constructor(private userService: UserService) {}
@Get()
list() {
return this.userService.findAll();
}
@Post()
create(@Body() data: { name: string }) {
return this.userService.create(data);
}
}
// Bootstrap
const app = createApp();
const router = createRouter();
await app.plugin(
controllersPlugin({
router,
root: './src',
prefix: '/api',
})
);
app.route('/', router);
await listen(app, 3000);When to Use
Choose the paradigm that fits your application:
- Building REST APIs with multiple endpoints - Need dependency injection for services - Want structured, testable code - Team prefers class-based patterns - Larger codebases with shared services
- Building simple APIs - Prototyping - You want minimal moving parts - Prefer functional programming
Setup Requirements
Auto-Import with nextrush
The nextrush meta-package auto-imports reflect-metadata. If you use nextrush, no manual
setup is needed beyond these tsconfig.json settings.
If using individual @nextrush/* packages, install reflect-metadata separately:
$ pnpm add reflect-metadata
// main.ts - FIRST LINE (only needed without the nextrush meta-package)
import 'reflect-metadata';
import { createApp } from '@nextrush/core';
// ... rest of importsEnable decorators in tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Next Steps
- @nextrush/di — Learn the DI container
- @nextrush/decorators — Explore all decorators