Skip to content

Events, Testing & API Reference ​

Events ​

Lifecycle events are notification-only. Use them for metrics, cache invalidation, and downstream notifications, not as authoritative proof that a database transaction committed. For atomic lifecycle evidence, use the 0.7 bridge with auditLifecycle: 'atomic-required' and withAuditTransaction().

Enable events and install @nestjs/event-emitter:

bash
npm install @nestjs/event-emitter
typescript
// app.module.ts
import { Module } from '@nestjs/common';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { SoftDeleteModule } from '@nestarc/soft-delete';
import { EXTENDED_PRISMA, PrismaModule } from './prisma.module';

@Module({
  imports: [
    EventEmitterModule.forRoot(),
    PrismaModule,
    SoftDeleteModule.forRoot({
      softDeleteModels: ['User', 'Post'],
      enableEvents: true,
      prismaServiceToken: EXTENDED_PRISMA,
    }),
  ],
})
export class AppModule {}

Use the exported client provider from installation, configured for the same models. Listen to events with @OnEvent():

typescript
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { SoftDeletedEvent, RestoredEvent, PurgedEvent } from '@nestarc/soft-delete';

@Injectable()
export class LifecycleListener {
  @OnEvent(SoftDeletedEvent.EVENT_NAME)
  onDeleted(event: SoftDeletedEvent) {
    console.log(`${event.model} soft-deleted by ${event.actorId} at ${event.deletedAt}`);
  }

  @OnEvent(RestoredEvent.EVENT_NAME)
  onRestored(event: RestoredEvent) {
    console.log(`${event.model} restored by ${event.actorId}`);
  }

  @OnEvent(PurgedEvent.EVENT_NAME)
  onPurged(event: PurgedEvent) {
    console.log(`${event.count} ${event.model} records purged (older than ${event.olderThan})`);
  }
}
Event classEVENT_NAMEPayload fields
SoftDeletedEventsoft-delete.deletedmodel, where, deletedAt, actorId, count?
RestoredEventsoft-delete.restoredmodel, where, actorId, count?
PurgedEventsoft-delete.purgedmodel, count, olderThan

Version 0.5 populates the optional count for bulk delete and bulk restore operations. Single-row soft deletes report count: 1; single-row restores keep the field optional for backward compatibility.

typescript
@OnEvent(RestoredEvent.EVENT_NAME)
onRestored(event: RestoredEvent) {
  metrics.count('soft_delete.restored', event.count ?? 1, {
    model: event.model,
  });
}

Notification-only contract ​

@nestjs/event-emitter dispatches these events synchronously by default, but an event may still be observed before an outer Prisma transaction commits. Listener failure, asynchronous scheduling, process termination, or a later rollback can therefore make event delivery diverge from durable database state. Do not call AuditService.log() from a listener and treat the result as atomic evidence.

For tenant-scoped audit evidence, use tenancy 0.16.4, audit-log 0.8.0, and soft-delete 0.7.6. Apply audit-log before soft-delete on the lifecycle client and inject that client into SoftDeleteModule. Configure auditLifecycle: 'atomic-required', bound bulk conversion with auditMaxBatchRecords, and pass tenancyTransactionCallback() to withAuditTransaction() before starting any lifecycle writes. Atomic lifecycle setup.


Testing ​

For application integration tests on 0.7.6, register the production SoftDeleteModule with an imported provider module, just as the application does. Import assertions from @nestarc/soft-delete/testing, and give them the unextended database client so they can read both active and deleted rows.

typescript
import { Module } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import type { TestingModule } from '@nestjs/testing';
import {
  expectSoftDeleted,
  expectNotSoftDeleted,
  expectCascadeSoftDeleted,
} from '@nestarc/soft-delete/testing';
import {
  SoftDeleteModule,
  SoftDeleteService,
  createPrismaSoftDeleteExtension,
} from '@nestarc/soft-delete';
import { basePrisma } from './prisma';
import { prismaDmmf } from './prisma.dmmf';

const TEST_PRISMA = Symbol('TEST_PRISMA');
const options = {
  softDeleteModels: ['User', 'Post'],
  cascade: { User: ['Post'] },
  dmmf: prismaDmmf,
};
const prisma = basePrisma.$extends(createPrismaSoftDeleteExtension(options)) as unknown as
  Omit<typeof basePrisma, '$on' | '$use'>;

@Module({
  providers: [{ provide: TEST_PRISMA, useValue: prisma }],
  exports: [TEST_PRISMA],
})
class TestPrismaModule {}

describe('UsersService', () => {
  let module: TestingModule;
  let softDelete: SoftDeleteService;

  beforeAll(async () => {
    module = await Test.createTestingModule({
      imports: [
        SoftDeleteModule.forRootAsync({
          imports: [TestPrismaModule],
          prismaServiceToken: TEST_PRISMA,
          useFactory: () => ({ ...options, prismaServiceToken: TEST_PRISMA }),
        }),
      ],
    }).compile();
    softDelete = module.get(SoftDeleteService);
  });

  afterAll(async () => {
    await module.close();
    await basePrisma.$disconnect();
  });

  it('soft-deletes and restores a user', async () => {
    // Seed an active User with id 1 in this test's isolated database first.
    await prisma.user.delete({ where: { id: 1 } });
    await expectSoftDeleted(basePrisma.user, { id: 1 });

    await softDelete.restore('User', { id: 1 });
    await expectNotSoftDeleted(basePrisma.user, { id: 1 });
  });

  it('cascades soft-delete to posts', async () => {
    // Seed an active User with id 2 and its Posts in an isolated fixture first.
    await prisma.user.delete({ where: { id: 2 } });
    await expectCascadeSoftDeleted(basePrisma, 'User', { id: 2 }, ['Post']);

    // The generic helper does not verify that children belong to this parent.
    const children = await basePrisma.post.findMany({ where: { authorId: 2 } });
    expect(children.length).toBeGreaterThan(0);
    expect(children.every((post) => post.deletedAt !== null)).toBe(true);
  });
});

basePrisma is your generated, adapter-backed Prisma client, owned and closed by this test suite. Seed and clean an isolated fixture for each test; adapt authorId to the actual relation field. Because this example enables cascade, load prismaDmmf as shown in the DMMF setup.

TestSoftDeleteModule in 0.7.5 ​

Version 0.7.5 shares the root and /testing service classes, injection tokens, event emitter, and context store within each module format. Load both entry points with CommonJS or both with ESM; this does not establish identity between a CommonJS root and an ESM testing entry point.

For a service fixture, replace the production-module registration above with:

typescript
import { TestSoftDeleteModule } from '@nestarc/soft-delete/testing';
import { SoftDeleteService } from '@nestarc/soft-delete';

const module = await Test.createTestingModule({
  imports: [TestSoftDeleteModule.register(options, prisma)],
}).compile();
const softDelete = module.get(SoftDeleteService);

Reuse the same options, extended prisma, raw-client assertions, and fixture cleanup from the example above. The test module installs the production cascade provider when cascade is configured; pass explicit DMMF to both the extension and test module. Missing DMMF fails module initialization. It remains a lightweight service fixture and does not install production HTTP middleware or interceptors. Keep the production module when testing those HTTP integrations.

Upgrading from 0.7.4

The 0.7.4 /testing bundles contain separate service classes and context stores and omit the cascade provider. For that older version, retain the production-module setup above. Upgrade to 0.7.5 or later before using the test module with root service tokens, root-extension context, or cascade restore. The release's installed-consumer checks cover CommonJS and ESM separately, shared context, Nest injection, cascade restore, and public types.

Assertion helpers ​

HelperDescription
expectSoftDeleted(delegate, where, deletedAtField?)Asserts the record exists and deletedAt is non-null.
expectNotSoftDeleted(delegate, where, deletedAtField?)Asserts the record exists and deletedAt is null.
expectCascadeSoftDeleted(prisma, parentModel, where, childModels, deletedAtField?)Asserts the selected parent is deleted and each listed child model has at least one deleted row; does not check foreign keys, all expected children, or unrelated rows.

Release compatibility checks ​

The 0.7.6 source checkout retains its published audit-log 0.4.1 / tenancy 0.15.0 development baseline. npm run test:e2e runs the baseline PostgreSQL suite, while npm run test:consumer:testing verifies the packed root/testing boundary for CommonJS and ESM. These are source-checkout commands, not commands supplied by the installed npm package.

The candidate runner builds and packs soft-delete, installs the selected packages with strict peer resolution, and verifies their Node.js engine ranges and artifact integrity. Run it on Node.js 22.23.4 or 24.22.1 with DATABASE_URL pointing to a disposable PostgreSQL database; the source E2E suite creates and clears its fixture tables.

bash
# Published composition: tenancy 0.16.4, audit-log 0.8.0, Prisma 7.10.1 consumer.
npm run test:tenancy-candidate:unit
npm run test:e2e:tenancy-candidate -- \
  --report /tmp/soft-delete-lifecycle-report.json

# Exercise the same packages with a Prisma 6 packed consumer.
npm run test:e2e:tenancy-candidate -- \
  --prisma-version 6.19.3 \
  --report /tmp/soft-delete-prisma6-report.json

# Check an explicit tenancy candidate with the latest audit package.
npm run test:e2e:tenancy-candidate -- \
  --tenancy-tarball /absolute/path/to/tenancy-candidate.tgz \
  --audit-log-version 0.8.0 \
  --report /tmp/soft-delete-candidate-report.json

The JSON report records exact versions, artifact sources, and integrity. --tenancy-version and --tenancy-tarball are mutually exclusive; a tarball without an explicit audit-log version retains the legacy audit-log baseline. --prisma-version selects the packed consumer's Prisma version; source E2E tests retain the repository toolchain.

The release fixture uses a restricted PostgreSQL role and FORCE RLS to check concurrent tenant isolation, missing or changed tenant rejection, restore and permanent deletion, and rollback on user or audit-write failure. CI runs Node.js 22.23.4 / 24.22.1 × Prisma 6.19.3 / 7.10.1; tagged publication runs both the baseline suite and the latest composition before publishing.


API Reference ​

@nestarc/soft-delete ​

ExportKindDescription
SoftDeleteModuleModuleNestJS dynamic module. Use .forRoot() or .forRootAsync().
SoftDeleteServiceServicerestore(), restoreMany(), forceDelete(), purge(), withDeleted(), onlyDeleted().
SoftDeleteContextServiceAsyncLocalStorage context for filter mode.
createPrismaSoftDeleteExtensionFunctionCreates a Prisma client extension for standalone use.
WithDeletedDecoratorInclude soft-deleted records in the route handler's queries.
OnlyDeletedDecoratorReturn only soft-deleted records in the route handler's queries.
SkipSoftDeleteDecoratorBypass soft-delete logic in the route handler.
WithDeletedRelationsDecoratorInclude deleted rows for exact to-many relation paths when relation filtering is enabled.
SoftDeleteFilterInterceptorInterceptorReads route metadata and sets the SoftDeleteContext. Auto-registered.
SoftDeletedEventClassEvent emitted after a soft-delete. EVENT_NAME = 'soft-delete.deleted'.
RestoredEventClassEvent emitted after a restore. EVENT_NAME = 'soft-delete.restored'.
PurgedEventClassEvent emitted after a purge. EVENT_NAME = 'soft-delete.purged'.
SoftDeleteEventEmitterServiceInternal emitter; exposed for advanced use.
SoftDeleteFieldMissingErrorErrorExported error reserved for missing-field validation; current runtime paths surface missing fields as Prisma errors.
CascadeRelationNotFoundErrorErrorThrown when a cascade relation cannot be resolved.
CascadeDmmfMissingErrorErrorThrown when cascade is configured without available DMMF metadata.
RelationDmmfMissingErrorErrorThrown when relation filters are enabled without available DMMF metadata.
SoftDeleteModuleOptionsInterfaceOptions for forRoot().
SoftDeleteModuleAsyncOptionsInterfaceOptions for forRootAsync().
SoftDeleteExtensionOptionsInterfaceOptions for createPrismaSoftDeleteExtension().
RelationFilterOptionsInterfaceEnables relation filtering and bounds traversal depth.
PrismaDmmfLikeInterfaceMinimal DMMF shape accepted by explicit configuration.

@nestarc/soft-delete/testing ​

ExportKindDescription
TestSoftDeleteModuleModuleLightweight service fixture with shared root/testing tokens and context within each module format in 0.7.5; installs configured cascade providers, without production HTTP middleware/interceptors.
expectSoftDeletedFunctionAssert a record is soft-deleted.
expectNotSoftDeletedFunctionAssert a record is not soft-deleted.
expectCascadeSoftDeletedFunctionAssert the selected parent and some deleted rows in each child model; verify parent-child relationships separately.

For complete signatures, see the generated @nestarc/soft-delete API and testing API.

Documentation site: MIT License. Check each package for its license.