npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@decaf-ts/for-nest

v0.14.1

Published

NestJS decaf integration

Downloads

2,365

Readme

Banner

Typescript Template

This repository is meant to provide an enterprise template for any standard Typescript project

Release docs refreshed on 2025-11-26. See workdocs/reports/RELEASE_NOTES.md for ticket summaries.

Licence GitHub language count GitHub top language

Build & Test CodeQLSnyk Analysis Pages builder .github/workflows/release-on-tag.yaml

Open Issues Closed Issues Pull Requests Maintained

Forks Stars Watchers

Node Version NPM Version

Documentation available here

Minimal size: 14.8 KB kb gzipped

Description

No one needs the hassle of setting up new repos every time.

Now you can create new repositories from this template and enjoy having everything set up for you.

How to Use


Module Configuration

DecafModule.forRootAsync(options)

The main entry point. Boots persistence, registers controllers, and wires the request pipeline.

import { DecafModule } from "@decaf-ts/for-nest";

@Module({
  imports: [
    DecafModule.forRootAsync({
      conf: [
        [FabricClientAdapter, fabricConfig, new FabricTransformer()],
        [TypeORMAdapter, pgConfig, new TypeORMTransformer()],
        [NanoAdapter, couchConfig, new NanoTransformer()],
      ],
      autoControllers: true,
      aggregations: false,
      handlers: [ImpersonateHandler],
      controllerExposure: { Product: true, Batch: ["hlf-fabric"] },
      controllerConfig: { Product: { auth: { public: true } } },
      observerOptions: { enableObserverEvents: true },
      initialization: async () => { await Service.boot(); },
    }),
  ],
})
export class AppModule {}

DecafModuleOptions

| Option | Type | Required | Default | Description | |---|---|---|---|---| | conf | [Constructor<Adapter>, ConfigOf<Adapter>, ...any[], Transformer?][] | Yes | — | Array of adapter tuples: [AdapterClass, adapterConfig, ...args, transformer?]. The trailing transformer (instance or constructor) maps request context fields to adapter-specific keys. If omitted, the adapter's registered @requestToContextTransformer is used. | | autoControllers | boolean | Yes | — | When true, auto-generates CRUD controllers for all models registered to each adapter flavour. | | autoServices | boolean | No | false | When true, generates a ModelService provider for every tracked model (injectable as ${ModelName}Service). | | aggregations | boolean | No | true | When false, disables grouping/aggregation routes globally by setting allowGroupingQueries: false as a globalDefaults override. | | controllerExposure | Record<string, boolean \| string[]> | No | — | Per-model exposure overrides. true exposes on all flavours; an array of flavour strings restricts exposure; false hides the model. When omitted, the @expose decorator metadata is used. | | controllerConfig | Record<string, ModelControllerFactoryConfig> | No | — | Per-model controller factory config. Merged on top of decorator-level @controllerConfig and globalDefaults. See ModelControllerFactoryConfig below. | | observerOptions | ObserverEventsOptions | No | — | SSE observer event configuration. See ObserverEventsOptions below. | | handlers | Type<DecafRequestHandler>[] | No | [] | Request handlers executed by DecafHandlerExecutor before the controller method. Each handler receives (context, req, res). | | initialization | () => Promise<void> | No | — | Called once after persistence boots but before the Nest module finishes initializing. Use for Service.boot() or similar setup. | | alias | string | No | — | Optional adapter alias for multi-instance scenarios. |

ModelControllerFactoryConfig

Per-controller knobs merged in this priority order (later wins):

  1. globalDefaults (from aggregations: false)
  2. @controllerConfig() decorator on the model class
  3. controllerConfig[modelName] in DecafModuleOptions

| Option | Type | Default | Description | |---|---|---|---| | allowStatementlessQuery | boolean | false | Allows @query() methods without a matching @statement() to be exposed as GET routes. | | allowGroupingQueries | boolean \| GroupingQueryFlags | true | Enables or fine-tunes aggregation endpoints (count, avg, max, min, sum, distinct, group). Set to false to hide all aggregation routes. | | allowBulkStatement | boolean \| BulkStatementFlags | false | Enables or fine-tunes bulk CRUD routes (bulk path: GET=readAll, PUT=updateAll, DELETE=deleteAll). | | auth | AuthConfig | — | Per-controller auth configuration. See AuthConfig below. |

GroupingQueryFlags: { count?: boolean; avg?: boolean; max?: boolean; min?: boolean; sum?: boolean; distinct?: boolean; group?: boolean }

BulkStatementFlags: { create?: boolean; read?: boolean; update?: boolean; delete?: boolean }

AuthConfig

Applied at the class level to every auto-generated controller for that model:

| Option | Type | Default | Description | |---|---|---|---| | public | boolean | false | When true, applies @Public() — the AuthInterceptor skips authorization entirely. | | roles | string[] | — | When provided, applies @RequireRoles(...roles) — the auth handler validates the user has all listed roles. | | namespaces | string[] | — | When provided, applies @RequireNamespaces(...namespaces) — the auth handler validates the user has all listed namespace scopes. | | skipModelRoles | boolean | false | When true, sets SKIP_MODEL_ROLES_KEY metadata — the AuthInterceptor passes undefined as the model to authHandler.authorize(), so model-level @roles() checks are skipped. Route-level roles (if set) still apply. | | skipModelNamespaces | boolean | false | When true, sets SKIP_MODEL_NAMESPACES_KEY metadata — the AuthInterceptor skips model-level @namespace() checks while still enforcing route-level namespaces. |

If auth is omitted, @Auth(Model) is applied by default (requires authentication + model-level role checks).

ObserverEventsOptions

| Option | Type | Default | Description | |---|---|---|---| | enableObserverEvents | boolean | false | Enables SSE stream events globally. | | observerFlavours | any[] | all registered | List of adapter flavours that will emit stream events. | | observerApiPath | string | "/events" | SSE endpoint path. |


Auth Configuration

DecafAuthModule.forRoot(options)

Optional standalone module for registering auth wiring independently of DecafCoreModule.

import { DecafAuthModule } from "@decaf-ts/for-nest";

@Module({
  imports: [
    DecafAuthModule.forRoot({
      global: true,
      handler: MyAuthHandler,
    }),
  ],
})
export class AppModule {}

Note: DecafCoreModule (booted via DecafModule.forRootAsync) already registers DecafRequestHandlerInterceptor as a global APP_INTERCEPTOR. DecafAuthModule does not duplicate this registration.

DecafAuthModuleOptions

| Option | Type | Default | Description | |---|---|---|---| | global | boolean | false | When true, registers AuthInterceptor as a global APP_INTERCEPTOR (via useExisting) and marks the module as @Global(). When false, AuthInterceptor is provided but only activated on routes decorated with @Auth() or @RequireRoles(). | | handler | Type<AuthHandler> | — | Concrete auth handler class. Registered both as itself and under the AUTH_HANDLER token. |

Manual Auth Wiring (without DecafAuthModule)

For full control, wire auth directly in your module:

import { AUTH_HANDLER, AuthInterceptor } from "@decaf-ts/for-nest";
import { APP_INTERCEPTOR } from "@nestjs/core";

@Global()
@Module({
  providers: [
    AuthInterceptor,
    AuthService,
    FabricKeycloakAuthHandler,
    { provide: AUTH_HANDLER, useClass: FabricKeycloakAuthHandler },
    { provide: APP_INTERCEPTOR, useExisting: AuthInterceptor },
  ],
  exports: [AUTH_HANDLER, AuthInterceptor, AuthService],
})
export class AuthModule {}

Auth Decorators

@Auth(model?)

Applies ApiBearerAuth(), UseInterceptors(AuthInterceptor), and (when a model is given) sets AUTH_META_KEY metadata so the handler knows which model is being accessed.

@Auth(Product)
@Controller("product")
export class ProductController {}

@Public()

Marks a route or controller as public — AuthInterceptor skips authorization.

@Public()
@Get("health")
health() { return { status: "ok" }; }

@RequireRoles(...roles)

Requires the user to have all listed roles. Applies ApiSecurity("bearer"), SetMetadata(REQUIRED_ROLES_KEY, roles), and UseInterceptors(AuthInterceptor).

@RequireRoles("admin", "writer")
@Put("product/:id")
update() {}

@RequireNamespaces(...namespaces)

Namespace-scope counterpart to @RequireRoles(...). Requires the user to have all listed namespace scopes. Applies ApiSecurity("bearer"), SetMetadata(REQUIRED_NAMESPACES_KEY, namespaces), and UseInterceptors(AuthInterceptor).

@RequireNamespaces("tenant:acme", "org:engineering")
@Get("tenant-data")
listTenantData() {}

@SkipFabricIdentity() (application-specific)

Application-level decorator (e.g. in ew-backend) that sets metadata to skip Fabric identity re-enrollment for specific routes. Not part of for-nest.


Auth Handler

AuthHandler<EC, C, D>

Abstract base class from @decaf-ts/for-http/server. Concrete handlers extend it and override:

| Method | Required | Description | |---|---|---| | extractFromAuth(ctx: EC): D \| Promise<D> | Yes | Pulls auth data (user, roles, organization) from the platform execution context. MUST throw AuthorizationError when unauthenticated. | | bindToContext(ctx: C, data: D) | Yes* | Binds auth data to the request context. Default implementation calls ctx.accumulate(data). Override to add adapter-specific keys (e.g. UUID, organization). | | validate(data, routeRoles, routeNamespaces, skipModelNamespaces, model, ...args) | No | Default validates route roles, route namespaces, model-level roles, and model-level namespaces (from @namespace()). Override for custom logic. |

* The default bindToContext exists but every concrete handler typically overrides it.

import { AuthHandler } from "@decaf-ts/for-nest";
import { AuthorizationError } from "@decaf-ts/core";

class CustomAuthHandler extends AuthHandler {
  protected extractFromAuth(ctx: ExecutionContext) {
    const req = ctx.switchToHttp().getRequest();
    const token = req.headers.authorization?.split(" ")[1];
    if (!token) throw new AuthorizationError("Unauthenticated");
    return { user: "alice", roles: ["admin"] };
  }

  protected bindToContext(ctx: DecafRequestContext, data: AuthData) {
    ctx.accumulate({ UUID: data.user, user: data.user });
  }
}

Namespace authorization

Use the namespace(...) decorator exported from @decaf-ts/integrations/nest on models to attach namespace scopes in the same way @roles(...) attaches model roles. The AuthInterceptor forwards those scopes to AuthHandler.authorize(...), and the base auth handler checks them against the authenticated principal.

import { namespace } from "@decaf-ts/integrations/nest";

@namespace(["tenant:acme", "org:engineering"])
class Product extends Model {}

Route-level namespace guards can be layered with @RequireNamespaces(...) and skipped at the model level with skipModelNamespaces: true in AuthConfig.

AuthData / UserData

| Field | Type | Description | |---|---|---| | user | string | Authenticated user identifier. | | roles | string[] | Roles granted to the user. | | namespaces | string[] | Namespace scopes granted to the user. | | organization | string | Organization / tenant / MSP. |


Auth Interceptor Flow

Request → AuthInterceptor → DecafRequestHandlerInterceptor → Controller
  1. AuthInterceptor (request-scoped):

    • Reads IS_PUBLIC_KEY — if true, skips auth.
    • Reads AUTH_META_KEY (model name), REQUIRED_ROLES_KEY (route roles), and REQUIRED_NAMESPACES_KEY (route namespaces).
    • Reads SKIP_MODEL_ROLES_KEY and SKIP_MODEL_NAMESPACES_KEY to selectively skip model-level role or namespace checks.
    • Calls authHandler.authorize(ctx, effectiveModel, requiredRoles, requiredNamespaces, skipModelNamespaces, requestContext).
    • Runs applyTransformers() — iterates Adapter.flavoursToTransform(), instantiates each RequestToContextTransformer if needed, calls transformer.from(requestContext), and accumulates the result.
    • Enriches the logger with user / organization if present.
  2. DecafRequestHandlerInterceptor (request-scoped, registered by DecafCoreModule):

    • Calls contextualize(req) — accumulates headers, logger, timestamp, operation into the request context.
    • Calls executor.exec(req, res) — runs all registered DecafRequestHandler instances in sequence.

Webhook Module

DecafWebhookModule.forRootAsync(options)

Standalone module for webhook delivery. Boots its own persistence layer (separate from DecafModule).

import { DecafWebhookModule } from "@decaf-ts/for-nest";

@Module({
  imports: [
    DecafWebhookModule.forRootAsync({
      conf: [[NanoAdapter, couchConfig, new NanoTransformer()]],
      webhookApiPath: "/webhooks",
      handlers: [WebhookAuthHandler],
    }),
  ],
})
export class AppModule {}

DecafWebhookModuleOptions

| Option | Type | Required | Default | Description | |---|---|---|---|---| | conf | same as DecafModuleOptions.conf | Yes | — | Adapter tuples for webhook persistence. | | handlers | Type<DecafRequestHandler>[] | No | [] | Request handlers for the webhook pipeline. | | initialization | () => Promise<void> | No | — | Called after webhook persistence boots. | | webhookApiPath | string | No | "/webhooks" | Router prefix for webhook controllers. |


Migration execution

DecafCoreModule.migrate wraps MigrationService.migrateAdapters once the persistence layer is ready. Use it to orchestrate upgrades across the adapters you boot in DecafCoreModule.bootPersistence.

const migrations = await DecafCoreModule.migrate({
  flavours: ["nano", "type-orm"],
  taskMode: true,
  taskService,
});

for (const migration of migrations) {
  await migration.track();
}

Passing taskMode: true causes each semver bump to become a tracked CompositeTask. Boot a dedicated RamAdapter and TaskService (never share the task engine alias with migrating adapters) before calling migrate, and make sure your version handlers (retrieveLastVersion / setCurrentVersion) live inside the module that owns the adapter.

From the CLI, the same flow is exposed as npx decaf nest migrate. Example:

npx decaf nest migrate \
  --input ./dist/app.module.js \
  --flavour nano,type-orm \
  --to 1.2.0 \
  --task-mode \
  --dry-run=false

The application bootstrap path is exposed as npx decaf nest boot. It delegates to lib/main, so a Docker image can keep the CLI as the single entrypoint while still reusing the same binary for migrate and export-api.

npx decaf nest boot --help

DecafCoreModule.migrate consults the migration handlers you registered per flavour (retrieveLastVersion/setCurrentVersion) so it always knows the current persisted head before building the execution plan. When taskMode is enabled each version is enqueued as a tracked CompositeTask; immediately after each task resolves MigrationService.track() calls setCurrentVersion for that version so the stored currentVersion equals the last fully applied hop. Failed tasks leave the version untouched, allowing MigrationService.retry(taskId) (optionally observed via taskService.track(id)) to reset the TaskModel to PENDING, clear its error/lease metadata, and replay only the incomplete version before proceeding.

In inline (non-task) mode the version marker updates only once after the entire batch completes, whereas task mode updates after each version so the next run always resumes at the correct semantic boundary even if an earlier version already succeeded. Specify toVersion (CLI --to) to define your goal; MigrationService filters migrations to those whose normalized versions fall strictly between the persisted currentVersion and the requested target so every run progressively walks the system through its lifecycle.

Control precedence through the @migration decorator:

  • reference: the canonical label (typically semver) used in logs and dependency hints.
  • precedence: point to another migration (constructor, token, or object) to force ordering between migrations with identical version/flavour.
  • flavour: restricts the migration to a given adapter flavour ("nano", "type-orm", "hlf-fabric", ...).
  • rules: async predicates (qr, adapter, ctx) that gate execution; if a rule returns false the migration is skipped without failing the run.

Keep your TaskEngine on a RamAdapter alias that never overlaps the adapters being migrated so lease metadata stays isolated, and let MigrationService track each version to ensure currentVersion only advances after a migration succeeds.

The CLI boots the Nest context without opening HTTP ports, creates a RamAdapter task engine (decaf-cli-task-engine), attaches the logger to every queued migration tracker, and waits on migration.track() before shutting down the task service, adapter, and Nest app. CLI flags always win over decaf.migration entries inside package.json. --dry-run remains a compatibility flag and no longer skips persistence.

Refer to the CLI module for how to boot the command runner; this migration command is implemented inside for-nest and reuses the DecafCoreModule.migrate wiring described above.

Coding Principles

  • group similar functionality in folders (analog to namespaces but without any namespace declaration)
  • one class per file;
  • one interface per file (unless interface is just used as a type);
  • group types as other interfaces in a types.ts file per folder;
  • group constants or enums in a constants.ts file per folder;
  • group decorators in a decorators.ts file per folder;
  • always import from the specific file, never from a folder or index file (exceptions for dependencies on other packages);
  • prefer the usage of established design patters where applicable:
    • Singleton (can be an anti-pattern. use with care);
    • factory;
    • observer;
    • strategy;
    • builder;
    • etc;

Release Documentation Hooks

Stay aligned with the automated release pipeline by reviewing Release Notes and Dependencies after trying these recipes (updated on 2025-11-26).

Related

Readme Card

Social

LinkedIn

Languages

TypeScript JavaScript NodeJS ShellScript

Getting help

If you have bug reports, questions or suggestions please create a new issue.

Contributing

I am grateful for any contributions made to this project. Please read this to get started.

Supporting

The first and easiest way you can support it is by Contributing. Even just finding a typo in the documentation is important.

Financial support is always welcome and helps keep both me and the project alive and healthy.

So if you can, if this project in any way. either by learning something or simply by helping you save precious time, please consider donating.

License

This project is released under the MIT License.

By developers, for developers...