Core Concepts / Modules

Modules

Organize your application into cohesive, composable blocks.

Modules group related controllers and providers into cohesive units. Every MiiaJS application has at least one root module.

Defining a module

typescript
import { Module } from '@miiajs/core'

@Module({
  controllers: [UserController],
  providers: [UserService],
})
class UserModule {}

Module options

OptionTypeDescription
controllersConstructor[]Controllers to register
providersProviderDefinition[]Services and other providers
imports(Constructor | ConfiguredModule | ForwardRef)[]Other modules to import; forwardRef(() => X) for module files that import each other
exports(Token | Constructor | ConfiguredModule | ForwardRef)[]What importers see: the module's own providers, and modules it imports (a re-export). Without it the module exports nothing - see Boundaries
globalbooleanMakes the exports visible to every module without an import
prefixstringPath prefix for all controllers - not the same thing as the app-level global prefix

Composing modules

Import modules to compose your application:

typescript
@Module({
  controllers: [UserController],
  providers: [UserService],
})
class UserModule {}

@Module({
  controllers: [PostController],
  providers: [PostService],
})
class PostModule {}

@Module({
  imports: [UserModule, PostModule],
  controllers: [HealthController],
  prefix: '/api',
})
class AppModule {}

A module sees its own providers and what its imports export - see Boundaries.

The prefix option prepends a path to all routes in the module and its imported modules:

/api
  /users    (from UserModule)
  /posts    (from PostModule)
  /health   (from AppModule)

A provider belongs to the module that declares it. The same provider in the providers of two modules throws and names both:

[Miia] MailService is provided by both UsersModule and OrdersModule - keep it in one module, add it to that module's exports, and import that module in the other

Module files that import each other

Two modules can import each other: the loader walks the graph once and follows the cycle without looping. The files are another matter. When users.module.ts imports orders.module.ts and the other way round, one file runs first and reaches the other's class before it is defined - a ReferenceError: Cannot access 'OrdersModule' before initialization, or an undefined in imports. Write the edge of the cycle as forwardRef(() => X), on both sides:

typescript
// users.module.ts
import { forwardRef, Module } from '@miiajs/core'
import { OrdersModule } from './orders.module.js'

@Module({
  imports: [forwardRef(() => OrdersModule)],
  providers: [UsersService],
})
export class UsersModule {}
typescript
// orders.module.ts
import { forwardRef, Module } from '@miiajs/core'
import { UsersModule } from './users.module.js'

@Module({
  imports: [forwardRef(() => UsersModule)],
  providers: [OrdersService],
})
export class OrdersModule {}

The loader calls the function once, when it processes the graph, and expects a module class or a configure() result. Wrap both sides: a forwardRef on one side only helps when its file happens to run second. An undefined in imports throws with the same advice:

[Miia] UsersModule imports undefined (index 0) - if two module files import each other, wrap both sides in forwardRef(() => X)

forwardRef is for imports between module files only. A cycle between providers - UsersService injects OrdersService, which injects UsersService - fails with [Miia] Circular dependency detected and its own advice, however the modules import each other.

Dynamic modules

Some modules need runtime configuration. Use the ConfiguredModule pattern:

typescript
export const DB_URL = createToken<string>('DB_URL')

class DatabaseModule {
  static configure(url: string): ConfiguredModule {
    return {
      module: DatabaseModule,
      providers: [
        {
          token: DB_URL,
          factory: () => url,
        },
        DatabaseService,
      ],
      exports: [DatabaseService],
    }
  }
}

A configure() result exports only what its exports lists - without it, nothing.

Use it in imports:

typescript
@Module({
  imports: [
    DatabaseModule.configure(process.env.DATABASE_URL),
  ],
})
class AppModule {}

Many MiiaJS packages use this pattern - ConfigModule.configure() (from @miiajs/config), DrizzleModule.configure(), JwtModule.configure(), PaprModule.configure().

Configure once, import bare

A configured module is identified by its class and an optional name. Configure it once, usually in the root module; a feature module that needs it imports the class bare and gets that configuration, whichever module the loader reaches first:

typescript
@Module({
  imports: [DatabaseModule], // the configuration from AppModule
  providers: [UserService],
})
class UsersModule {}

@Module({
  imports: [UsersModule, DatabaseModule.configure(process.env.DATABASE_URL)],
})
class AppModule {}

Configuring the same module twice without a name throws - [Miia] DatabaseModule is configured twice (...), naming the two modules that configure it - instead of silently keeping the first configuration. A configure() result is imported by one module: the same object in the imports of two modules, or of a module and app.register(), throws [Miia] The same configured module DatabaseModule is imported by AppModule and ReportsModule - import it once and re-export it from that module, or make it global. Other modules import the class bare. In tests, replace a configuration with TestApp.override(DatabaseModule, DatabaseModule.configure(testUrl)) (see Testing).

A module class configured under several names (configure() results { module: DatabaseModule, name: 'analytics' } and { module: DatabaseModule, name: 'logs' }) shares its own @Module parts between them. Its providers are one instance owned by every name: each name can export it, and what it injects is checked against boundaries from each name, so the result does not depend on the order of imports. So is a Resolver it injects: has() is true only for a token every name sees, and resolve() is checked from each name. Its controllers are mounted once, and what they inject and their guards are checked from every name too; every name must resolve them under the same prefix - otherwise startup throws [Miia] X (name 'b') resolves its controllers under /b, but X (name 'a') already mounted them under /a. A configure() result in its imports is imported once, hosted by the first name. Only the providers of each configure() result belong to that name; the same token in two of them, or in one of them and in @Module({ providers }), still throws.

Shared providers

A register()-style module - one that returns a new ConfiguredModule per call, like PaprModule.register([User]) - is often called by several feature modules for the same token. Declared plainly, that is provided by both. Mark the provider with provider(token, factory, { shared: key }) and the modules share it instead:

typescript
export const AUDIT_LOG = createToken<AuditLog>('AuditLog')

class AuditModule {
  static register(): ConfiguredModule {
    return {
      module: class AuditFeatureModule {},
      providers: [provider(AUDIT_LOG, () => new AuditLog(), { shared: 'audit' })],
      exports: [AUDIT_LOG],
    }
  }
}

@Module({ imports: [AuditModule.register()] })
class UsersModule {}

@Module({ imports: [AuditModule.register()] })
class OrdersModule {} // the same AuditLog instance as UsersModule

The first declaration the loader reaches builds the instance, and every declaring module owns it: each can export it, and what the factory injects is checked against boundaries from each of them, so the result does not depend on the order of imports. So is its Resolver: has() is true only for a token every declaring module sees, and resolve() is checked from each of them. Every declaration must carry the same key. A different key throws [Miia] AuditLog is shared by ... (audit) and ... (other) - a shared provider must be declared the same way in every module; use a separate token for each variant - the key names the variant there, which is why papr and mongoose key their models by connection (the default connection, connection 'analytics'). A declaration without shared next to a shared one, or one module listing the provider twice, throws as before.

Boundaries

All modules of an app share one DI container, but a module only sees part of it. A token is visible from a module when:

  • the module declares it (providers, controllers);
  • the module imports a module that lists it in exports;
  • an imported module re-exports a module that exports it, at any depth;
  • a global module exports it (directly or by re-export).

Built-in tokens (Router, DiscoveryService, Resolver, REQUEST_CONTEXT) and providers registered with app.provide() are visible to every module. Everything else is private to the module that declares it.

Exports and imports

typescript
@Module({
  providers: [UsersService, PasswordHasher],
  exports: [UsersService], // PasswordHasher stays private
})
class UsersModule {}

@Module({
  imports: [UsersModule],
  providers: [OrdersService], // can inject(UsersService), not PasswordHasher
})
class OrdersModule {}

exports lists the module's own providers, or modules it imports - a re-export: whoever imports this module sees what the re-exported module exports. Anything else throws at startup: [Miia] UsersModule exports MailService, which it neither provides nor imports.

typescript
@Module({ imports: [MailModule], exports: [MailModule] })
class NotificationsModule {} // importers see what MailModule exports

The root

app.register(AppModule, AdminModule) imports the modules into a virtual root, which owns nothing and sees what the registered modules export. What has no module of its own is checked from the root: a provider registered with app.provide() (its token is visible to everyone, but what it injects is checked from the root), a global guard from app.useGuard() that no module declares, and the factories of a configure() result passed to app.register() directly.

Global modules

global: true makes a module's exports visible to every module without an import. It is always explicit and has one form - @Module({ global: true }), global on a ConfiguredModule, or { global: true } in the second argument of a package's configure(). Nothing is global by default, packages included. Infrastructure almost every module reaches for - configuration, the database, JWT - is usually configured once in the root module with { global: true }.

A global module that re-exports another one makes those exports global too:

typescript
const config = ConfigModule.configure({ schema: EnvSchema })

@Module({ global: true, imports: [config], exports: [config] })
class CoreModule {}

Configured modules

A configure() result follows the same rules, with a few of its own:

  • Without exports it exports nothing. Listing the public providers is the job of whoever writes configure() - every MiiaJS package does.
  • The module that imports the configure() result sees its exports. Another module sees them when it is global, or by importing the class bare: imports: [DrizzleModule] reaches the configuration without a name, wherever it is configured.
  • A named configuration ({ name: 'analytics' }) has no bare import: make it global, or import the configure() result in the one module that uses it and re-export it from there.
  • Its factories - the options factory you pass to configure() and the providers it declares - see what the configured module sees plus what its host sees: the module whose imports hold the configure() result, or the root for app.register(). That is how DrizzleModule.configure((resolve) => ...) in AppModule reads a provider AppModule keeps private.

Guards

A guard declared in a module's providers is a provider like any other: a controller in another module can use it once the guard's module exports it and the controller's module imports that module. A guard that is both declared in a module and registered with app.useGuard() must be visible from the root - list it in the exports of a module passed to app.register().

A guard no module declares - a class put straight into @UseGuard() or app.useGuard(), AuthGuard(JwtAuth), @RateLimit() - has no module of its own. It is built once, and what it injects is checked from the module of every controller that uses it, and from the root when it is global:

AuthGuard(JwtAuth) (guard of UsersController in UsersModule) injects JwtAuth (AuthModule):
  - add JwtAuth to AuthModule `exports`
  - add AuthModule to UsersModule `imports`

See Guards → Guards and modules.

Resolver

inject(Resolver) returns a resolver bound to the module of the provider that injects it: has() answers for what that module sees, and resolve() of anything else is a violation like an inject() of it - see Providers → Resolver. app.get(Resolver), a provider registered with app.provide() and a guard no module declares get the resolver of the root.

The startup report

Boundaries are checked from the module of the provider that asks: every inject() and injectOptional() while a provider is constructed, every resolve() of a factory provider and every token in its deps, every Resolver call, and the guards of every controller. During startup a violation does not stop the app on the spot. init() processes the module graph, constructs every singleton and global guard, and throws one report before the first onInit() - before anything connects to a database:

[Miia] 2 module boundary violations:

OrdersService (OrdersModule) injects UsersService (UsersModule):
  - add UsersService to UsersModule `exports`
  - add UsersModule to OrdersModule `imports`

UsersService (UsersModule) injects drizzleDb() (DrizzleModule in AppModule), which is not global:
  - make it global: DrizzleModule.configure(options, { global: true })
  - or add DrizzleModule to UsersModule `imports`

Docs: /docs/core-concepts/modules#boundaries

app.get() before init() reports the same way, for the module graph and everything the token it resolves pulls in. An error that ends startup early - a missing provider, a cycle - carries the violations found before it: Also found 1 module boundary violation so far:. After a report the app does not start: every later init(), app.get() and request rethrows it.

injectOptional() returns null only for a token nothing registers. A registered token the module cannot see is a violation, not null.

After startup a violation throws at once: a transient or request-scoped provider built during a request, a Resolver call, or a factory's resolve() called later - say, by a lazy proxy on first use. That resolve stays bound to the provider it was given to and is checked from its module, whoever triggers the call.

What is not checked

  • Only what is constructed, listed in deps or resolved at runtime. A conditional inject() is checked when it runs, a request-scoped provider when the first request builds it.
  • Top-level resolution: app.get(), TestApp.resolve() and ctx.resolve() reach any token. What the provider they build injects is still checked from its own module.
  • DiscoveryService sees the classes of every module, exported or not - the metadata key is what scopes it.
  • What a guard no module declares reaches through another guard no module declares: only its own inject() calls are checked against the modules that use it.

Registering with the app

Register your root module with the Miia instance:

typescript
const app = new Miia()
  .register(AppModule)

await app.listen(3000)

You can register multiple modules:

typescript
const app = new Miia()
  .register(AppModule, FeatureModule)

Module loading order

  1. Registration - ModuleLoader processes all modules recursively, registering providers in the DI container
  2. Route resolution - Controllers are instantiated and routes are compiled into the router
  3. Construction - on init(), every other singleton is constructed; boundary violations from this step and the previous one make one report before the first onInit()
Edit this page on GitHub