Coming from NestJS
A mapping from NestJS constructs to Ulo's, a small NestJS controller ported, and the differences that change how code is written.
Ulo takes its architecture from NestJS: modules own controllers and providers, dependencies arrive through a container, and a request passes guards and interceptors on its way to a handler. A NestJS developer already knows how an Ulo application is laid out.
What changes is the language and what the compiler can check. Decorators become attribute macros, classes become structs, injection tokens become types, and the whole module graph is validated before the first instance exists.
The map
Declarations
| NestJS | Ulo |
|---|---|
@Module({ ... }) | #[module(...)] on a unit struct, or impl Module for X with a register(&self, m: &mut ModuleDef) method |
imports / controllers / providers / exports | The same four keys, with the same meaning |
@Global() | #[module(global, ...)] |
@Injectable() | #[injectable] on a struct (its fields are injected), or on an impl whose new takes the dependencies and may be async and fallible |
Scope.DEFAULT, Scope.REQUEST, Scope.TRANSIENT | #[injectable] (a singleton), #[injectable(execution)], #[injectable(transient)]; a controller or enhancer with no scope written becomes per-execution when it reads per-execution data, and a controller takes the same scopes on #[controller(execution)] |
@Controller('users') | #[controller] on the struct and #[handlers] on its impl; each route carries its full path |
@Get() @Post() @Put() @Delete() @Patch() @Head() @Options() | #[ulo_http::get("/users/{id}")] and post, put, delete, patch, head, options |
@Sse() | A #[ulo_http::get] handler returning Sse<..> |
@WebSocketGateway() / @SubscribeMessage('say') | #[ulo_ws::gateway(path = "/chat")] on the #[handlers] impl, and #[ulo_ws::message("say")] on the handler |
@MessagePattern() / @EventPattern() | #[ulo_rpc::message("calc.divide")] / #[ulo_rpc::event("calc.note")]; an event reaches one instance of a service by default, and #[ulo_rpc::event("calc.note", every_instance)] reaches every instance |
@GrpcMethod() | #[ulo_grpc::method(pb::catalog::GetItem)] |
@SetMetadata() + Reflector | #[meta(RequiresRole("admin"))], read in an enhancer with cx.exec().handler().and_then(|h| h.meta::<RequiresRole>()) |
Route parameters are spelled {id}. A controller takes no route prefix. The prefix is set at registration, in a hand-written module: m.controller::<UsersController>().at("/api"). Sources: examples 02-providers, 15-http-requests, 16-http-enhancers, 18-http-streaming, 23-ws-gateway, 25-rpc-basics, 29-grpc-service.
Enhancers
| NestJS | Ulo |
|---|---|
CanActivate | Guard<T>: async fn can_activate(&self, cx: &HttpCx) -> Result<bool, BoxError> |
NestInterceptor | Interceptor<T>: intercept(&self, cx, next), which calls next.run().await |
ExceptionFilter + @Catch() | ErrorHandler<T>: handle(&self, err: BoxError, cx), which downcasts and returns Err(err) to pass the error on |
NestMiddleware | Middleware, declared in module metadata (see below) |
@UseGuards() @UseInterceptors() @UseFilters() | #[guards(..)] #[interceptors(..)] #[error_handlers(..)] on the #[handlers] impl or on one method |
useGlobalGuards(), APP_GUARD | A contribution in a module's providers: into AnyGuard<Http>: [AuthGuard] |
HttpException | CallError::new(ErrorKind::NotFound, ".."), or a domain error implementing Classify |
ValidationPipe | Valid<Json<T>> with #[derive(Validate)] on T; a failure is a 422 |
A guard, interceptor or error handler is a type implementing the trait, and the role is read from the trait, so there is no marker attribute. An enhancer is written by type (#[guards(AuthGuard)]), by value (value = RateLimit::per_second(100)), or by closure (with = |t: Dep<Trace>| Stamp::new(t)). The stack order is global, then controller, then method. The same impl<T: Transport> Guard<T> can guard an HTTP route and an RPC message (example 41-one-guard-two-transports).
Reading the request
| NestJS | Ulo |
|---|---|
@Param('id') | Path(id): Path<u32> |
@Query() | Query<T> |
@Body() | Json<T>, or Form<T> |
@Body() + ValidationPipe | Valid<Json<T>> |
@Headers() | Header<H> for a typed header, HeaderMap for all |
@UploadedFile() | Multipart |
| Per-request data set by a guard | Ext<T>, read in a handler or an execution-scoped service |
Extractors are handler parameters, matched by type. See Extractors.
Custom providers
| NestJS | Ulo |
|---|---|
{ provide: Cfg, useValue: v } | A value in providers: Settings { salutation: "Hello" } |
{ provide: 'Repo', useClass: PgRepo } | PgUserRepo as dyn UserRepo in providers; injected as Dep<dyn UserRepo> |
{ provide: 'DB', useFactory: async (cfg) => .., inject: [Cfg] } | with = |cfg: Dep<Cfg>| async move { .. }; the closure's parameters are the dependency list |
@Inject('PRIMARY') | A qualifier type: Db("primary") @ Primary in providers, Dep<Db, Primary> at the injection point |
multi: true providers | into dyn Plugin: [MetricsPlugin, TracingPlugin], injected as Many<dyn Plugin> |
DynamicModule, forRoot() | A module that is a value: StoreModule::for_root(url). Equal values are one module; .keyed::<Q>() imports one module twice under two qualifiers |
Sources: examples 02-providers, 03-traits-and-qualifiers, 04-collections-and-optional, 07-configured-modules.
Lifecycle hooks
| NestJS | Ulo |
|---|---|
OnModuleInit | OnModuleInit: async fn on_module_init(&self) -> Result<(), BoxError> |
OnApplicationBootstrap | OnApplicationBootstrap |
OnModuleDestroy | OnModuleDestroy |
BeforeApplicationShutdown | BeforeApplicationShutdown, receiving &Signal |
OnApplicationShutdown | OnApplicationShutdown, receiving &Signal |
app.enableShutdownHooks() | Passing a signal future to serve: app.serve(shutdown_signal()) |
A hook is a trait implemented on a singleton provider, and #[injectable] registers whichever are implemented. A readiness check with retries is written against ModuleDef (example 09-lifecycle). A hook on an execution or transient type is a compile error. The shutdown order is on Production.
Platforms, transports and integrations
| NestJS | Ulo |
|---|---|
@nestjs/platform-express, -fastify | ulo-http-hyper, ulo-http-axum, ulo-http-actix, ulo-http-poem, ulo-http-rocket, ulo-http-salvo |
Transport.TCP / NATS / REDIS / RMQ / MQTT / KAFKA | ulo-rpc-tcp / -nats / -redis / -rabbitmq / -mqtt / -kafka (and ulo-rpc-udp) |
Transport.GRPC | ulo-grpc |
@nestjs/typeorm, @nestjs/mongoose | ulo-db-sqlx, ulo-db-seaorm, ulo-db-diesel, ulo-db-mongodb, ulo-db-redis |
@nestjs/config | ulo-config |
@nestjs/terminus | ulo-health with ulo-health-http or ulo-health-grpc |
@nestjs/graphql | ulo-graphql with ulo-graphql-async-graphql or ulo-graphql-juniper |
Test.createTestingModule() + overrideProvider() | TestApp::of(AppModule).override_value::<dyn Mailer>(Arc::new(fake)) |
A controller, ported
A NestJS controller with a service, validation and a typed 404:
@Controller('notes')
export class NotesController {
constructor(private readonly notes: NotesService) {}
@Post()
create(@Body() dto: CreateNoteDto) { return this.notes.add(dto.title); }
@Get(':id')
find(@Param('id', ParseIntPipe) id: number) {
const note = this.notes.find(id);
if (!note) throw new NotFoundException(`no note ${id}`);
return note;
}
}The same controller in Ulo, from examples/15-http-requests, which imports Dep and the macros from ulo, and Classify, Created, Json, Path, Valid and Validate from ulo_http:
#[derive(Deserialize, Validate)]
pub struct NewNote {
#[validate(length(min = 1, max = 20))]
pub title: String,
}
/// `#[classify(not_found)]` is the whole mapping: the answer is a 404 problem document.
#[derive(Debug, Classify)]
#[classify(not_found)]
pub struct NoteNotFound(pub u32);
impl fmt::Display for NoteNotFound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "no note {}", self.0)
}
}
impl std::error::Error for NoteNotFound {}
#[controller]
pub struct NotesController {
notes: Dep<Notes>,
}
#[handlers]
impl NotesController {
#[ulo_http::post("/notes")]
fn create(&self, Valid(Json(new)): Valid<Json<NewNote>>) -> Created<Json<Note>> {
let note = self.notes.add(new.title);
Created::at(format!("/notes/{}", note.id), Json(note))
}
#[ulo_http::get("/notes/{id}")]
fn find(&self, Path(id): Path<u32>) -> Result<Json<Note>, NoteNotFound> {
let all = self.notes.all.lock().unwrap();
all.iter().find(|note| note.id == id).cloned().map(Json).ok_or(NoteNotFound(id))
}
}
#[module(providers = [Notes], controllers = [NotesController])]
pub struct AppModule;- The constructor parameter becomes a
Dep<Notes>field.Dep<T>holds a sharedArc<T>, and cloning it clones the pointer. ParseIntPipehas no counterpart:Path<u32>parses, and a segment that does not parse is a client error before the handler runs.- The DTO class and
ValidationPipebecome a struct with#[derive(Validate)], wrapped inValid<..>at the parameter. throw new NotFoundExceptionbecomes returning the error.Classifymaps a domain error to anErrorKind, and the transport renders it (a 404application/problem+jsonon HTTP).- The bootstrap,
NestFactory.create(AppModule)andapp.listen(3000), is the sequence on Quick Start.
Where Ulo differs
The graph is validated before anything is built
wire() checks the whole module graph and reports every problem together: a provider that is not bound, a binding another module cannot see because it was not exported, an export of something the module does not bind, a module that imports itself, a dependency cycle, a scope mismatch, a duplicate binding. No instance exists yet and no I/O has happened. NestJS reports the first failure during bootstrap.
There is no forwardRef
Modules may import one another, because an import decides what a module sees and builds nothing. A dependency cycle between providers is a wiring error that prints the path, such as A → B → C → A, and the fix is to remove one dependency in it. Only a module importing itself is an ImportCycle.
Types are the tokens
An injection point is its type: Dep<T>, Dep<dyn Trait>, Option<Dep<T>>, Many<dyn Trait>. There is no @Inject(). Two instances of one type are told apart by a qualifier type, Dep<Db, Primary>. Visibility is the module's exports: a binding another module does not export is invisible to it, even if it imports the module.
Guards return a Result, and a refusal is an error value
can_activate returns Ok(true) to admit and Ok(false) to refuse. A refusal reaches the error handlers as a GuardRejected and renders 403 on HTTP when no handler claims it. A guard that wants another status returns its own error: Err(CallError::unauthorized("Bearer").into()) is a 401 with a WWW-Authenticate challenge. can_activate is async, so verification and lookups run inline.
Every error passes the error handlers
A handler returns Result<T, E> where E implements Classify or is a CallError. The error goes through the error handlers, method tier first, then controller, then global, before the transport renders it. An error that no handler claims renders from its ErrorKind, and an ErrorHandler changes that rendering. A panic in a guard, interceptor or handler is caught and becomes an Internal error through the same handlers.
Middleware is one app-wide stage, scoped by path
HTTP middleware is declared in a module's metadata, in a hand-written Module, because #[module] has no slot for it (example 17-http-pre-dispatch). Its entries apply to the whole application and are scoped by path pattern, not by module:
m.meta::<PreDispatch>()
.layer(served_by())
.apply_value(TagTenant)
.apply_value(Cors::new().allow_origin("https://app.example").allow_methods([Method::GET]))
.apply_for::<ApiKey>(["/admin/*"])
.exclude(["/admin/health"]);Unscoped entries run before routing, see misses, and can answer without calling next, which is how a CORS preflight is answered. Entries scoped with apply_for run after the route is matched and before the guards. Auth for a group of routes is a pattern-scoped entry.
Request scope means one execution
An execution-scoped provider is built once per execution: one HTTP request, one WebSocket message, one RPC or gRPC call, or one standalone execute. A WebSocket connection is not an execution, so per-connection state belongs in Session<T>. A singleton cannot depend on an execution-scoped provider, and wire() reports the dependency path. A controller or enhancer with no scope written (Auto) becomes per-execution when it reads per-execution data such as Ext<T>. A provider with no scope written stays a singleton, and wire() refuses it with a ScopeViolation if it reads that data.
Ext<T> and the execution scope are the counterpart of nestjs-cls: a value written once per request, by a guard or middleware, is read anywhere below it without being passed as an argument.
Startup is in phases
There is no app.listen(port). Building, wiring, connecting, binding servers, listening and serving are separate steps, and the server is a choice made in main (Server::new("0.0.0.0:8080")). wire() and listen() each report all their problems together, and listen() reports configuration problems before port conflicts. Shutdown hooks run when serve returns, and serve returns when its signal future resolves or close is called. See Deployment.
Macros are optional
Every macro expands to calls on a public value API (impl Module for X, ModuleDef::provide, Mount::handler). The lifecycle readiness checks, pre-dispatch metadata and keyed imports have no macro spelling and use it directly. Example 14-without-macros is example 06 written that way.
Next
- Quick Start: a route, served.
- Core Concepts: modules, providers, scopes.
- Request Lifecycle: the order of middleware, guards, interceptors, handler and error handlers.
For the NestJS topic list, section by section, see NestJS topics, mapped.