@cqrs-ddd/core 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,27 +8,7 @@ versioned mutations, detached domain events, a command handler that publishes th
8
8
  events, repository contracts, persistence lifecycle decorators, a revision-fenced
9
9
  repository cache, tenant-scoped cache keys and HTTP status mapping for its errors.
10
10
 
11
- It depends on no framework and no ORM. MikroORM adapters are in
12
- [`@cqrs-ddd/mikro-orm`](https://www.npmjs.com/package/@cqrs-ddd/mikro-orm). It works in a plain Node service, and in a NestJS
13
- application through structural compatibility: see [Using it from NestJS](#using-it-from-nestjs).
14
-
15
- ## Contents
16
-
17
- - [Installation](#installation)
18
- - [Entry points](#entry-points)
19
- - [Aggregates](#aggregates)
20
- - [Value rules](#value-rules)
21
- - [Domain events](#domain-events)
22
- - [Commands and event publication](#commands-and-event-publication)
23
- - [Write-side repositories](#write-side-repositories)
24
- - [Read-side repositories](#read-side-repositories)
25
- - [The repository cache](#the-repository-cache)
26
- - [Tenant-scoped cache keys](#tenant-scoped-cache-keys)
27
- - [HTTP status mapping](#http-status-mapping)
28
- - [Using it from NestJS](#using-it-from-nestjs)
29
- - [Moving from ddd/core](#moving-from-dddcore)
30
- - [Known limits](#known-limits)
31
- - [License](#license)
11
+ **Documentation:** [guide](https://aristoteliss.github.io/nestjs-pipeline/packages/cqrs-ddd/core/) · [API reference](https://aristoteliss.github.io/nestjs-pipeline/api/cqrs-ddd/core/) · [all packages](https://aristoteliss.github.io/nestjs-pipeline/)
32
12
 
33
13
  ## Installation
34
14
 
@@ -42,693 +22,7 @@ Requires Node.js 22.12 or later. It installs `@cqrs-ddd/uuidv7` and
42
22
  `@cqrs-ddd/safe-stringify`, which have no dependencies. To persist with MikroORM, add
43
23
  `@cqrs-ddd/mikro-orm` and `@mikro-orm/core` 7.
44
24
 
45
- Published as an ES module; a CommonJS application loads it with `require()`. Coming from
46
- 0.3.x, see [Upgrading from 0.3.x](https://github.com/aristoteliss/nestjs-pipeline#upgrading-from-03x).
47
-
48
- ## Entry points
49
-
50
- Import from the entry point for the layer you are writing. Each one loads only what it
51
- needs.
52
-
53
- | Entry | Holds |
54
- | --- | --- |
55
- | `@cqrs-ddd/core/domain` | `AggregateRoot`, `IAggregateRoot`, `ApplyEventOptions`, `RootEntity`, `RootEntitySnapshot`, `@Mutable`, `getMutableFields`, `@ApplyMutation`, `IEvent`, `DomainEvent`, `RootDomainEvent`, `deepCloneAndFreeze`, `textRule`, `numberRule`, `ValueViolation`, and the errors `DomainException`, `InvalidValueException`, `EntityNotFoundException`, `ConcurrencyConflictError`, `TransientOperationError` (with `isTransientOperationError`), `MissingTenantContextError`, `UnknownMutableFieldError` |
56
- | `@cqrs-ddd/core/application` | `BaseCommand`, `BaseQuery`, `IQueryOptions`, `CommandBaseHandler`, the ports (`IDomainEventPublisher`, `ICommandRepository`, `IQueryRepository`, `IWriteSideAggregateRepository`, `ICache`, `IVersionedCache`, `isVersionedCache`), `requireTenant`, `setTenantResolver`, and the deprecated `requireTenantId` |
57
- | `@cqrs-ddd/core/persistence` | the lifecycle decorators (`@PersistedWrite`, `@Cache`, `@AcknowledgePersisted`, `@MapPersistenceErrors`, `@FromCache`), `QueryRepository`, `CommandRepository`, `MemoryCache` and its injection token `CACHE_TOKEN`, `cacheKey`, `cacheKeyTemplate`, `isCacheNewer`, `toCacheSnapshot`, the mutation-barrier helpers, `consoleCacheLogger`, `safeWarn`, and the persistence dialect contract (`IPersistenceDialect`, `setPersistenceDialect`, `persistenceDialect`) |
58
- | `@cqrs-ddd/core/http` | `domainErrorHttpStatus` |
59
- | `@cqrs-ddd/core` | all of the above, plus the `Method` type |
60
-
61
- No entry point loads an ORM or NestJS.
62
-
63
- ## Aggregates
64
-
65
- An aggregate extends `RootEntity<TSnapshot>`. It gets a UUIDv7 `id`, `createdAt` and
66
- `updatedAt`, an optimistic-concurrency `version`, and an event buffer. State changes go
67
- through domain methods decorated with `@ApplyMutation`, which write only the fields
68
- declared `@Mutable`:
69
-
70
- ```typescript
71
- import {
72
- ApplyMutation,
73
- DomainException,
74
- InvalidValueException,
75
- Mutable,
76
- RootEntity,
77
- type RootEntitySnapshot,
78
- textRule,
79
- } from '@cqrs-ddd/core/domain';
80
-
81
- export class InvalidUsernameException extends InvalidValueException {}
82
- export class InvalidDepartmentException extends InvalidValueException {}
83
- export class EmptyUserUpdateException extends DomainException {
84
- constructor() {
85
- super('A user update needs at least one field.');
86
- }
87
- }
88
-
89
- export interface UserSnapshot extends Partial<RootEntitySnapshot> {
90
- readonly username: string;
91
- readonly email: string;
92
- readonly department?: string | null;
93
- }
94
-
95
- export class User extends RootEntity<UserSnapshot> {
96
- static readonly aggregateName = 'user';
97
- static readonly rules = {
98
- username: textRule({
99
- field: 'username',
100
- minLength: 3,
101
- maxLength: 255,
102
- error: (violation) => new InvalidUsernameException(violation),
103
- }),
104
- department: textRule({
105
- field: 'department',
106
- required: false,
107
- maxLength: 255,
108
- error: (violation) => new InvalidDepartmentException(violation),
109
- }),
110
- } as const;
111
-
112
- @Mutable<string>({ normalize: (value) => User.rules.username.parse(value) })
113
- private _username: string;
114
-
115
- @Mutable<string | null>({ normalize: (value) => User.rules.department.parse(value) })
116
- private _department: string | null;
117
-
118
- readonly email: string;
119
-
120
- private constructor(snapshot: UserSnapshot) {
121
- super(snapshot);
122
- this._username = User.rules.username.parse(snapshot.username);
123
- this._department = User.rules.department.parse(snapshot.department);
124
- this.email = snapshot.email;
125
- }
126
-
127
- static create(username: string, email: string, department?: string | null): User {
128
- const user = new User({ username, email, department });
129
- user.apply(new UserCreatedEvent(user));
130
- return user;
131
- }
132
-
133
- static fromJSON(snapshot: UserSnapshot): User {
134
- return new User(snapshot);
135
- }
136
-
137
- get username(): string {
138
- return this._username;
139
- }
140
-
141
- private set username(value: string) {
142
- this._username = User.rules.username.parse(value);
143
- }
144
-
145
- get department(): string | null {
146
- return this._department;
147
- }
148
-
149
- private set department(value: string | null) {
150
- this._department = User.rules.department.parse(value);
151
- }
152
-
153
- @ApplyMutation<User>({ event: (user) => new UserUpdatedEvent(user) })
154
- update(fields: { username?: string; department?: string | null }): this {
155
- if (fields.username === undefined && fields.department === undefined) {
156
- throw new EmptyUserUpdateException();
157
- }
158
- this.applyPatch({ username: fields.username, department: fields.department });
159
- return this;
160
- }
161
-
162
- @ApplyMutation<User>({ event: (user) => new UserDeletedEvent(user) })
163
- delete(): this {
164
- return this;
165
- }
166
-
167
- toJSON(): UserSnapshot & RootEntitySnapshot {
168
- return this.freezeState({
169
- id: this.id,
170
- username: this._username,
171
- department: this._department,
172
- email: this.email,
173
- createdAt: this.createdAt,
174
- updatedAt: this.updatedAt,
175
- version: this.version,
176
- });
177
- }
178
- }
179
- ```
180
-
181
- The events are declared in [Domain events](#domain-events). Using the aggregate:
182
-
183
- ```typescript
184
- const user = User.create('alice', 'alice@example.test');
185
- user.version; // 1
186
- user.getUncommittedEvents(); // [UserCreatedEvent]
187
-
188
- user.update({ department: 'Research' });
189
- user.version; // 2
190
- user.getExpectedVersion(); // 1: the version the next write must find in storage
191
-
192
- user.update({}); // throws EmptyUserUpdateException; nothing is recorded
193
- user.update({ username: 'a' }); // throws InvalidUsernameException before any field is written
194
- ```
195
-
196
- - `@Mutable` registers a field for `applyPatch` under its property name without a
197
- leading underscore (`_username` is patched as `username`); `as: 'name'` sets another
198
- key, and `normalize` validates and converts each value.
199
-
200
- - `applyPatch(patch)` validates and normalizes every supplied field before writing any
201
- of them, and ignores `undefined` values. An unknown key throws `UnknownMutableFieldError`.
202
- - After a successful method, `@ApplyMutation` advances `version` and `updatedAt` and
203
- records the event. A method that throws records nothing.
204
- - Validate before patching: a failure after the fields are written (later method code,
205
- a lifecycle hook, event creation) does not roll them back. Discard or reload the
206
- instance.
207
- - `RootEntity.from(value)` rehydrates an instance, a snapshot or a nullish database
208
- result, and throws a `TypeError` for an incompatible aggregate.
209
- - `id`, `createdAt` and `updatedAt` have public getters and private setters. The ORM
210
- hydrates through the setters (see below); application code cannot assign them and
211
- changes state through domain methods and factories. Give a subclass's own persisted
212
- fields private setters too, as `username` and `department` above.
213
- - `version` is the in-memory version; `getExpectedVersion()` is the version last read
214
- from or written to storage, which a version-conditioned write compares against.
215
- `acknowledgePersisted()` moves it forward after a successful write; `@PersistedWrite`
216
- calls it for you.
217
-
218
- ## Value rules
219
-
220
- `textRule(options)` and `numberRule(options)` define the rule for one field once. The
221
- aggregate uses the rule's `parse(value)` to normalize the value, and other layers read
222
- the rule's limits, so a request schema cannot drift from the domain:
223
-
224
- ```typescript
225
- z.string().trim().min(User.rules.username.minLength).max(User.rules.username.maxLength);
226
- ```
227
-
228
- `parse(value)` returns the normalized value or throws the rule's error. It is a
229
- standalone function, and the rule is frozen.
230
-
231
- | `textRule` option | Effect |
232
- | --- | --- |
233
- | `field` | Name reported in the violation and in the default message |
234
- | `required` | `false` normalizes `null`, `undefined` and blank text to `null`; by default they are rejected |
235
- | `minLength`, `maxLength` | Length after normalization, in UTF-16 code units like Zod's `.min()` and `.max()` |
236
- | `pattern` | Regular expression the text must match; a `g` or `y` flag is rejected |
237
- | `multiline` | `true` accepts tab, line feed and carriage return inside the text |
238
- | `error` | Builds the error for a violation; defaults to `InvalidValueException` |
239
-
240
- Text is checked for type and unpaired surrogates, then put in Unicode NFC form and
241
- trimmed. Control characters are always rejected, and so are tabs and line breaks unless
242
- `multiline` is set.
243
-
244
- | `numberRule` option | Effect |
245
- | --- | --- |
246
- | `field`, `required`, `error` | As for `textRule` (`required: false` accepts `null` and `undefined`) |
247
- | `integer` | Accepts safe integers only |
248
- | `min`, `max` | Inclusive bounds |
249
-
250
- A number must be of type `number` and finite; a numeric string is rejected, not
251
- converted. An invalid option, such as `minLength` above `maxLength`, throws a
252
- `TypeError` when the rule is defined.
253
-
254
- A broken rule throws `error(violation)`. `violation` is a frozen `ValueViolation`:
255
- `{ field, rule }`, plus `limit` for a length or range rule and `expected` for a type
256
- rule. `InvalidValueException` carries it, builds the message (`username must be at
257
- least 3 characters.`), and does not keep the rejected value. Extend it for your own
258
- exceptions, as in the example above, so every one shares that shape.
259
-
260
- ## Domain events
261
-
262
- A domain event extends `RootDomainEvent<TEntity, TPayload>`. It carries a UUIDv7 `id`,
263
- the event-time `aggregateId` and `aggregateVersion`, and `payload`: a deep clone of the
264
- aggregate's `toJSON()`, recursively frozen.
265
-
266
- ```typescript
267
- import { RootDomainEvent } from '@cqrs-ddd/core/domain';
268
-
269
- export class UserCreatedEvent extends RootDomainEvent<User, UserSnapshot> {
270
- constructor(user: User) {
271
- super(user);
272
- }
273
- }
274
- ```
275
-
276
- `UserUpdatedEvent` and `UserDeletedEvent` are declared the same way.
277
-
278
- - **Detached:** later changes to the aggregate never reach `payload`.
279
- - **Read-only for ordinary access:** own properties are frozen, and the mutating methods
280
- of cloned `Date`, `Map` and `Set` values throw.
281
- - **Not a security boundary:** `Object.freeze` does not cover built-in internal state,
282
- so `Date.prototype.setTime.call(payload.at, 0)` still changes it, and every consumer
283
- of one event shares the same `payload`. `event.clonePayload()` returns a fresh frozen
284
- copy per call when a consumer needs its own.
285
- - **Not a transport format:** send an explicit, serializable message built from the
286
- fields you need.
287
-
288
- `deepCloneAndFreeze(value)` is the function behind `payload`, also usable on its own. It
289
- handles objects, arrays, `Date`, `Map`, `Set`, `RegExp` and circular references.
290
-
291
- ## Commands and event publication
292
-
293
- `BaseCommand` and `BaseQuery` are plain base classes for command and query objects.
294
- `BaseCommand` keeps an optional `sessionPrincipal` (or `sessionUser`) out of enumeration and `toJSON()`, so it
295
- never reaches a fingerprint or a log. `getUpdateFields(fields)` returns the listed
296
- fields the command carries (`null` counts, `undefined` does not), for field-level
297
- authorization.
298
-
299
- `CommandBaseHandler` runs a command and publishes the events of the aggregate it
300
- returns:
301
-
302
- ```typescript
303
- import {
304
- BaseCommand,
305
- CommandBaseHandler,
306
- type IDomainEventPublisher,
307
- type IWriteSideAggregateRepository,
308
- } from '@cqrs-ddd/core/application';
309
- import { EntityNotFoundException } from '@cqrs-ddd/core/domain';
310
-
311
- export class UpdateUserCommand extends BaseCommand {
312
- constructor(
313
- readonly id: string,
314
- readonly username?: string,
315
- readonly department?: string | null,
316
- ) {
317
- super();
318
- }
319
- }
320
-
321
- export class UpdateUserHandler extends CommandBaseHandler<UpdateUserCommand, User> {
322
- constructor(
323
- private readonly users: IWriteSideAggregateRepository<User>,
324
- eventBus: IDomainEventPublisher,
325
- ) {
326
- super(eventBus);
327
- }
328
-
329
- async handle(command: UpdateUserCommand): Promise<User> {
330
- const user = await this.users.findById(command.id);
331
- if (!user) throw new EntityNotFoundException('User', command.id);
332
- user.update({ username: command.username, department: command.department });
333
- await this.users.save(user);
334
- return user;
335
- }
336
- }
337
-
338
- const handler = new UpdateUserHandler(users, {
339
- publishAll: async (events) => events.forEach((event) => emitter.emit('event', event)),
340
- });
341
- await handler.execute(new UpdateUserCommand(id, 'bob'));
342
- ```
343
-
344
- - `handle()` returns the aggregate, or a result carrying it as `aggregate`; any
345
- `IAggregateRoot` qualifies. `execute()` calls it, publishes the buffered events once
346
- with `eventBus.publishAll(events, aggregate)` (the aggregate is the dispatcher context),
347
- clears the buffer and returns the result unchanged.
348
- - A rejected `handle()` publishes nothing. If `publishAll()` throws, the error
349
- propagates and the events stay buffered.
350
- - If `publishAll()` returns a promise, `execute()` waits for it after clearing the buffer.
351
- Its rejection rejects the command, although the aggregate is already persisted; the
352
- events are not published a second time.
353
- - Any object with `publishAll(events)` is an `IDomainEventPublisher`.
354
-
355
- **`AggregateRoot.commit()` publishes nothing by default.** It hands a copy of the
356
- buffer to the aggregate's own `publishAll` hook (`apply()` calls `publish` while
357
- `autoCommit` is on), which does nothing until a publisher is connected, then clears the
358
- buffer. Calling `commit()` without a connected publisher therefore drops the events; so
359
- does `autoCommit`. Let `CommandBaseHandler` publish, or read `getUncommittedEvents()` and
360
- call `uncommit()` yourself.
361
-
362
- `commit(dispatcherContext?)` passes the context, such as `{ transaction }`, to
363
- `publishAll` and returns what it returns. The buffer is cleared once `publishAll`
364
- returns, before an asynchronous publisher settles, so `await aggregate.commit()` waits
365
- for the publisher and receives its error without risking a second publication; if
366
- `publishAll` throws, the events stay buffered.
367
-
368
- ## Write-side repositories
369
-
370
- A command handler loads the authoritative aggregate through
371
- `IWriteSideAggregateRepository<TEntity>.findById(id)`: it must read primary storage, never
372
- a cache. `@cqrs-ddd/mikro-orm`'s `AggregateRepository` implements it for MikroORM.
373
-
374
- `save()` declares its lifecycle with `@PersistedWrite`. With `@cqrs-ddd/mikro-orm`, where
375
- `AggregateRepository` provides `findById()` and `this.store`:
376
-
377
- ```typescript
378
- import type { ICache } from '@cqrs-ddd/core/application';
379
- import { DomainException } from '@cqrs-ddd/core/domain';
380
- import { cacheKey, PersistedWrite } from '@cqrs-ddd/core/persistence';
381
- import {
382
- AggregateRepository,
383
- type IEntityManagerSource,
384
- mapPersistenceError,
385
- optimisticUpdate,
386
- } from '@cqrs-ddd/mikro-orm';
387
-
388
- export class UniqueEmailException extends DomainException {
389
- constructor(readonly user: User) {
390
- super('This email is already registered.');
391
- }
392
- }
393
-
394
- export class UpdateUserRepository extends AggregateRepository<UserSnapshot, User, UserSnapshot> {
395
- constructor(cache: ICache<UserSnapshot>, store: IEntityManagerSource) {
396
- super(cache, store, User, User.aggregateName, User.fromJSON);
397
- }
398
-
399
- @PersistedWrite<User>({
400
- cache: {
401
- setKey: (user) => cacheKey(User.aggregateName, { id: user.id }),
402
- invalidateKeys: (user) => [cacheKey(User.aggregateName, { email: user.email })],
403
- },
404
- unique: { email: (user) => new UniqueEmailException(user) },
405
- otherwise: (error, user) => mapPersistenceError(error, `updating User ${user.id}`),
406
- })
407
- async save(user: User): Promise<UserSnapshot> {
408
- const snapshot = user.toJSON();
409
- await optimisticUpdate(
410
- this.store.em,
411
- User,
412
- user,
413
- {
414
- username: snapshot.username,
415
- department: snapshot.department ?? null,
416
- updatedAt: snapshot.updatedAt,
417
- },
418
- 'User',
419
- );
420
- return snapshot;
421
- }
422
- }
423
- ```
424
-
425
- `optimisticUpdate` adds `version` to the written fields; every other changed column,
426
- `updatedAt` included, is listed explicitly.
427
-
428
- `@PersistedWrite` applies three decorators. Stacked by hand, the order is fixed,
429
- outermost first:
430
-
431
- 1. `@Cache(options)`: after a successful write, writes the returned snapshot through
432
- with a compare-and-set (`isCacheNewer` unless `isNewer` says otherwise), and
433
- installs barriers for `invalidateKeys`.
434
- When `save()` resolves `null` or `undefined`, it installs barriers for `deleteKeys`.
435
- Cache errors are logged and never turn a committed write into a failure.
436
- 2. `@AcknowledgePersisted({ entity: ([aggregate]) => aggregate })`: advances the
437
- selected aggregate's persisted version only after the write succeeded.
438
- 3. `@MapPersistenceErrors({ entity, unique, dialect, otherwise })`: translates a unique
439
- violation into your domain error. `unique` is keyed by the entity property the
440
- constraint covers (`{ email: ... }`), or by the declared name of a multi-column
441
- constraint (`MapPersistenceErrors<Args, Entity, typeof NAME>`), so a repository never
442
- names a database constraint or column. Which constraint an error violated is read by
443
- the persistence dialect: `options.dialect`, else the one registered with
444
- `setPersistenceDialect()` at the composition root. Core knows no database; an adapter
445
- such as `MikroOrmDialect` of `@cqrs-ddd/mikro-orm` implements `IPersistenceDialect`.
446
- A method that declares `unique` with no dialect available throws a `TypeError` before
447
- it runs. `otherwise` translates the rest, for example with `mapPersistenceError` of
448
- `@cqrs-ddd/mikro-orm`, which turns retryable driver and network failures into
449
- `TransientOperationError` and keeps every other error unchanged.
450
-
451
- Deletes do not acknowledge, so they stack `@Cache` and `@MapPersistenceErrors` alone,
452
- and resolve `null` so `@Cache` installs barriers for `deleteKeys`:
453
-
454
- ```typescript
455
- import { Cache, cacheKey, MapPersistenceErrors } from '@cqrs-ddd/core/persistence';
456
- import { mapPersistenceError, optimisticDelete } from '@cqrs-ddd/mikro-orm';
457
-
458
- export class DeleteUserRepository extends AggregateRepository<UserSnapshot, User, null> {
459
- constructor(cache: ICache<UserSnapshot>, store: IEntityManagerSource) {
460
- super(cache, store, User, User.aggregateName, User.fromJSON);
461
- }
462
-
463
- @Cache<User, null>({
464
- deleteKeys: (user) => [
465
- cacheKey(User.aggregateName, { id: user.id }),
466
- cacheKey(User.aggregateName, { email: user.email }),
467
- ],
468
- })
469
- @MapPersistenceErrors<[User], User>({
470
- entity: ([user]) => user,
471
- otherwise: (error, user) => mapPersistenceError(error, `deleting User ${user.id}`),
472
- })
473
- async save(user: User): Promise<null> {
474
- await optimisticDelete(this.store.em, User, user, 'User');
475
- return null;
476
- }
477
- }
478
- ```
479
-
480
- The write itself must be version-conditioned (`WHERE id = ? AND version = expected`) and
481
- must not run inside an outer transaction, whose success would not mean durable
482
- persistence. `@cqrs-ddd/mikro-orm` provides `optimisticUpdate` and `optimisticDelete`
483
- for this.
484
-
485
- ## Read-side repositories
486
-
487
- A query repository extends `QueryRepository` and decorates `find()` with `@FromCache`. The
488
- constructor takes the cache (any `ICache`; see [The repository cache](#the-repository-cache)
489
- for why `@FromCache` needs an `IVersionedCache`) and the repository's default hydration:
490
-
491
- ```typescript
492
- import { BaseQuery, type ICache, type IQueryOptions } from '@cqrs-ddd/core/application';
493
- import { cacheKey, FromCache, QueryRepository } from '@cqrs-ddd/core/persistence';
494
- import type { IEntityManagerSource } from '@cqrs-ddd/mikro-orm';
495
-
496
- export class GetUserQuery extends BaseQuery {
497
- constructor(
498
- readonly id: string,
499
- options?: IQueryOptions,
500
- ) {
501
- super(options);
502
- }
503
- }
504
-
505
- export class GetUserRepository extends QueryRepository<GetUserQuery, User | null> {
506
- constructor(
507
- cache: ICache<UserSnapshot>,
508
- private readonly store: IEntityManagerSource,
509
- ) {
510
- super(cache, { hydrateFn: (cached) => User.fromJSON(cached as UserSnapshot) });
511
- }
512
-
513
- @FromCache<GetUserQuery, User | null>({
514
- keyFn: (query) => cacheKey(User.aggregateName, { id: query.id }),
515
- })
516
- async find(query: GetUserQuery): Promise<User | null> {
517
- return this.store.em.findOne(User, { id: query.id }, query.refresh ? { refresh: true } : undefined);
518
- }
519
- }
520
-
521
- await users.find(new GetUserQuery(id)); // may be served from the cache
522
- await users.find(new GetUserQuery(id, { refresh: true })); // always reads the database
523
- ```
524
-
525
- `@FromCache` options: `keyFn` (return `null` to skip the cache for that call),
526
- `hydrateFn`, `serializeFn`, `ttl` in milliseconds, `isNewer` and `logger`.
527
-
528
- - Every hit is rehydrated whenever a hydrator applies, so a hit and a miss return the
529
- same type. A method's own `hydrateFn` (or `hydrateFn: null`) overrides the
530
- repository's; `serializeFn` follows the same rule.
531
- - Without a hydrator, only plain data is cached; a class instance is returned uncached.
532
- - Only non-nullish results are stored. A barrier or a stored `null` counts as a miss.
533
- - A query with `refresh: true` bypasses the cache.
534
- - Cache errors propagate from reads: a query fails rather than guessing.
535
-
536
- ## The repository cache
537
-
538
- `@Cache` works with any `ICache` (`get`, `set`, `delete`). `@FromCache` requires an
539
- `IVersionedCache`, which adds a revision fence:
540
-
541
- | Method | Contract |
542
- | --- | --- |
543
- | `readState(key)` | the entry's status (`hit`, `miss`, `expired`), value and opaque revision |
544
- | `invalidate(key)` | evicts the value and advances the revision |
545
- | `tryFill(key, observedRevision, value, options?)` | writes only if the revision is still `observedRevision`; `false` otherwise |
546
-
547
- `@FromCache` observes the revision before the database read and fills with `tryFill`, so
548
- a read that raced an invalidation or a delete cannot write a stale snapshot back. A
549
- rejected fill re-reads the key, returns a strictly newer snapshot if one is there, and
550
- otherwise retries a bounded number of times before returning the database result
551
- uncached. **An adapter that implements only `ICache` is bypassed by `@FromCache` for
552
- both reads and fills**, with a warning logged once: it cannot fence a fill.
553
-
554
- Two adapters implement `IVersionedCache`:
555
-
556
- - `MemoryCache({ defaultTtlMs = 60_000, maxEntries = 10_000 })`: in process, entries
557
- JSON-cloned on write and read, for tests and a single process.
558
- - `MikroOrmCache`, in `@cqrs-ddd/mikro-orm`: one database row per key, every write a
559
- compare-and-set in its own transaction.
560
-
561
- `CacheSetOptions.isNewer(cached, incoming)` returns `true` when the cached value is
562
- newer and must not be overwritten; `isCacheNewer` compares `version`, then `__gen`, then
563
- `updatedAt`. `toCacheSnapshot` turns a result into a detached snapshot: the cache never
564
- stores a live aggregate.
565
-
566
- Mutation barriers (`CacheMutationBarrier`) mark a deleted or invalidated key for
567
- `barrierTtl`, 60 seconds by default. Size it above your longest in-flight read.
568
-
569
- **The `logger` option.** `@Cache` and `@FromCache` accept `logger: { warn(message) }`
570
- for their operational warnings, such as a failed cache write, a bypassed adapter or a
571
- miswired repository. A NestJS `Logger` or `console` fits. Without one, warnings go to
572
- `console.warn`. A logger that throws never changes a result. An adapter reports its own
573
- warnings the same way through `consoleCacheLogger(context)` and `safeWarn(logger, message)`.
574
-
575
- ## Tenant-scoped cache keys
576
-
577
- `cacheKey(resource, conditions, tenant?)` and `cacheKeyTemplate(template, tenant?)`
578
- namespace every key by tenant. The tenant comes from, in order:
579
-
580
- 1. the explicit `tenant` argument: a tenant id string, or an object carrying `tenantId`,
581
- such as a request context;
582
- 2. for `cacheKeyTemplate`, a context source's `tenantId`;
583
- 3. the resolver the application registers once at startup with `setTenantResolver(fn)`,
584
- a function that returns the tenant of the running request or job;
585
- 4. otherwise, `MissingTenantContextError`.
586
-
587
- ```typescript
588
- import { AsyncLocalStorage } from 'node:async_hooks';
589
- import { setTenantResolver } from '@cqrs-ddd/core/application';
590
-
591
- const requestTenant = new AsyncLocalStorage<string>();
592
- setTenantResolver(() => requestTenant.getStore());
593
-
594
- // Per request or job:
595
- requestTenant.run(tenantId, () => handle(request));
596
- ```
597
-
598
- There is no shared namespace: a missing or empty tenant, or a resolver that returns
599
- nothing, throws. A single-tenant deployment passes a fixed id or registers
600
- `setTenantResolver(() => 'single')`. The same resolution is public as
601
- `requireTenant(purpose, source?)`, for any other key that must be partitioned by
602
- tenant, such as an idempotency or rate-limit key, and for any code that needs the
603
- current tenant and must fail when there is none:
604
-
605
- ```typescript
606
- import { requireTenant } from '@cqrs-ddd/core/application';
607
-
608
- requireTenant('access token issuance'); // the resolver's tenant
609
- requireTenant('users.create idempotency key', ctx); // ctx.tenantId, else the resolver's
610
- ```
611
-
612
- `requireTenantId(source, purpose)` is deprecated: it takes the same arguments in the
613
- reverse order and calls `requireTenant`.
614
-
615
- `cacheKey` keys have the form `${tenant}:${resource}:v1:${sha256}`, hashed over a
616
- key-sorted serialization of `[tenant, resource, conditions]`. The format is frozen, so
617
- stored entries stay addressable across releases.
618
-
619
- ## HTTP status mapping
620
-
621
- `domainErrorHttpStatus(error)` from `/http` maps this package's errors to plain
622
- `{ statusCode, error, message }` values, for any HTTP framework:
623
-
624
- | Error | Status |
625
- | --- | --- |
626
- | `ConcurrencyConflictError` | 409 |
627
- | `EntityNotFoundException` | 404 |
628
- | `MissingTenantContextError` | 500, with a generic message: a request without a tenant is a server fault |
629
- | any other `DomainException`, `InvalidValueException` included | 400 |
630
-
631
- It returns `undefined` for anything else. Map your own exceptions first, then pass the
632
- rest to it.
633
-
634
- ## Using it from NestJS
635
-
636
- Nothing in this package imports NestJS; the fit is structural.
637
-
638
- - The NestJS CQRS `EventBus` has `publishAll(events, dispatcherContext)`, so it is an
639
- `IDomainEventPublisher`: a handler passes its injected bus to `super(eventBus)`, and
640
- the bus hands the aggregate to its configured publisher as the dispatcher context.
641
- - `AggregateRoot` satisfies NestJS's `IAggregateRoot`, and a NestJS `AggregateRoot`
642
- satisfies this package's `IAggregateRoot`. `EventPublisher.mergeObjectContext(aggregate)`
643
- connects an aggregate to the `EventBus`: `commit()` then publishes with the aggregate as
644
- the context, `commit({ transaction })` with that context, and both return the bus's
645
- result.
646
- - `CommandBaseHandler.execute(command)` is the method the NestJS command bus calls, so a
647
- class decorated with `@CommandHandler` extends it directly.
648
- - `BaseCommand`, `BaseQuery` and the domain events are plain classes that NestJS
649
- dispatches like any other.
650
-
651
- ```typescript
652
- @CommandHandler(UpdateUserCommand)
653
- export class UpdateUserHandler extends CommandBaseHandler<UpdateUserCommand, User> {
654
- constructor(
655
- @Inject(USER_WRITE_REPOSITORY) private readonly users: IWriteSideAggregateRepository<User>,
656
- eventBus: EventBus,
657
- ) {
658
- super(eventBus);
659
- }
660
- // handle() as above
661
- }
662
- ```
663
-
664
- The application writes the rest of the glue:
665
-
666
- - providers for the repositories and the cache, for example a `useFactory` provider
667
- that builds a `MikroOrmCache` from `@cqrs-ddd/mikro-orm` under `CACHE_TOKEN`:
668
-
669
- ```typescript
670
- { provide: CACHE_TOKEN, useValue: new MemoryCache({ defaultTtlMs: 30_000 }) }
671
- ```
672
-
673
- - the tenant resolver, registered once before any lifecycle hook can start work that
674
- reads it, for example in a module constructor;
675
- - an exception filter that maps its own errors, then calls `domainErrorHttpStatus`;
676
- - a `logger` for the cache decorators, such as `new Logger('UserCache')`.
677
-
678
- ## Moving from ddd/core
679
-
680
- The unpublished workspace package `@nestjs-pipeline/ddd-core` (directory `ddd/core`) maps
681
- onto this package as follows. It depended on NestJS and MikroORM; this package depends on
682
- neither, and the MikroORM parts are in `@cqrs-ddd/mikro-orm`.
683
-
684
- | `ddd/core` | `@cqrs-ddd/core` |
685
- | --- | --- |
686
- | `import { … } from '@nestjs-pipeline/ddd-core'` | the layer entry points: `@cqrs-ddd/core/domain`, `/application`, `/persistence`, `/http` |
687
- | `@Mutate()` on a mutation method, which called `onUpdate()` | `@ApplyMutation({ event })`, which also records the event, plus `@Mutable` fields written through `applyPatch()` |
688
- | `DomainOutcome`, `RootDomainOutcome` returned by `handle()` | `handle()` returns the aggregate, or a result with an `aggregate` property; its buffered events are published |
689
- | `CommandBaseHandler(eventBus: EventBus)` from `@nestjs/cqrs` | `CommandBaseHandler(eventBus: IDomainEventPublisher)`; a NestJS `EventBus` still fits |
690
- | `CacheableEntity`, `ICacheKey`, `entity.cacheKey` (`prefix + id`) | `RootEntity` with a static `aggregateName`, keys built with `cacheKey(User.aggregateName, { id })`, always tenant-scoped |
691
- | `CacheableEntity.fromStringify(data, fromJSON)` | `RootEntity.from(value)` or the aggregate's own `fromJSON` |
692
- | `ICommandRepository.save(domainOutcome)` | `ICommandRepository.save(entity)`, and `IWriteSideAggregateRepository.findById(id)` for loading |
693
- | `@Cache(setKeyFn, deleteKeysFn)` | `@Cache({ setKey, deleteKeys, invalidateKeys, ttl, isNewer, barrierTtl, logger })`, usually through `@PersistedWrite` |
694
- | `@FromCache(keyFn, hydrateFn)`, hydrating when `query.hydrate` is set | `@FromCache({ keyFn, hydrateFn, … })` with an `IVersionedCache`; hits are always rehydrated when a hydrator applies |
695
- | `QueryRepository(cache)` | `QueryRepository(cache, { hydrateFn, serializeFn? })` |
696
- | `ICache` in `persistence/cache.interface` | `ICache` and `IVersionedCache` in `@cqrs-ddd/core/application` |
697
- | `UnixTimestampType` | `UnixTimestampType` in `@cqrs-ddd/mikro-orm` |
698
- | `RootEntity` with an abstract `afterUpdate()` | `afterUpdate()` is an optional hook; `RootEntity` extends `AggregateRoot` and adds `version`, `getExpectedVersion()`, the event buffer and private hydration setters |
699
-
700
- The old imports and the new ones side by side:
701
-
702
- ```typescript
703
- // ddd/core
704
- import { CacheableEntity, CommandBaseHandler, Mutate, RootDomainOutcome } from '@nestjs-pipeline/ddd-core';
705
-
706
- // @cqrs-ddd/core
707
- import { ApplyMutation, Mutable, RootEntity } from '@cqrs-ddd/core/domain';
708
- import { CommandBaseHandler } from '@cqrs-ddd/core/application';
709
- import { cacheKey, PersistedWrite } from '@cqrs-ddd/core/persistence';
710
- import { AggregateRepository, optimisticUpdate, UnixTimestampType } from '@cqrs-ddd/mikro-orm';
711
- ```
712
-
713
- ## Known limits
714
-
715
- - Persistence and event publication are not atomic. A crash between the write and
716
- `publishAll()` loses the events; durable delivery needs an outbox.
717
- - Cache maintenance after a commit is best-effort. If an invalidation fails, the
718
- previous entry stays until it expires: the revision fence coordinates the cache with
719
- itself, not with the database. Read with `{ refresh: true }` where a decision must
720
- not rest on a cached value.
721
- - A mutation barrier protects only for `barrierTtl`. It is a bounded race window, not a
722
- tombstone.
723
- - The persistence helpers reject outer transactions; decorators cannot make several
724
- writes atomic. A row that must commit with the aggregate, such as an audit record or
725
- an outbox message, therefore cannot share its transaction yet: that needs commit
726
- hooks that run acknowledgment and cache work after the commit.
727
- - `@MapPersistenceErrors` maps a unique violation only as well as the registered
728
- persistence dialect reads it; `MikroOrmDialect` reads PostgreSQL and SQLite errors.
729
- - The tenant resolver is process-wide: one per process, for each installed copy of this
730
- package.
731
- - Event payloads are frozen for ordinary access only; see [Domain events](#domain-events).
25
+ Published as an ES module; a CommonJS application loads it with `require()`. Coming from 0.3.x, see [Upgrading from 0.3.x](https://aristoteliss.github.io/nestjs-pipeline/upgrading/from-0-3/).
732
26
 
733
27
  ## License
734
28
 
@@ -165,7 +165,7 @@ export declare abstract class RootEntity<TSnapshot extends Partial<RootEntitySna
165
165
  * }
166
166
  * ```
167
167
  *
168
- * @example Declarative invocation via `@AcknowledgePersisted` (recommended)
168
+ * @example Declarative invocation through the AcknowledgePersisted decorator (recommended)
169
169
  * ```typescript
170
170
  * @AcknowledgePersisted<[User]>({ entity: ([user]) => user })
171
171
  * async save(user: User): Promise<UserSnapshot> {
@@ -256,7 +256,7 @@ export class RootEntity extends AggregateRoot {
256
256
  * }
257
257
  * ```
258
258
  *
259
- * @example Declarative invocation via `@AcknowledgePersisted` (recommended)
259
+ * @example Declarative invocation through the AcknowledgePersisted decorator (recommended)
260
260
  * ```typescript
261
261
  * @AcknowledgePersisted<[User]>({ entity: ([user]) => user })
262
262
  * async save(user: User): Promise<UserSnapshot> {
@@ -10,7 +10,7 @@ import { ICommandRepository } from '../application/ports/command-repository.port
10
10
  * @typeParam TEntity - The aggregate entity type accepted by {@link save}.
11
11
  * @typeParam TResult - The persisted result type returned by {@link save}.
12
12
  *
13
- * @example Creating a command repository with @Cache
13
+ * @example Creating a command repository with the Cache decorator
14
14
  * ```typescript
15
15
  * @Injectable()
16
16
  * export class CreateUserCommandRepository extends CommandRepository<User, UserSnapshot> {
@@ -9,7 +9,7 @@
9
9
  * @typeParam TEntity - The aggregate entity type accepted by {@link save}.
10
10
  * @typeParam TResult - The persisted result type returned by {@link save}.
11
11
  *
12
- * @example Creating a command repository with @Cache
12
+ * @example Creating a command repository with the Cache decorator
13
13
  * ```typescript
14
14
  * @Injectable()
15
15
  * export class CreateUserCommandRepository extends CommandRepository<User, UserSnapshot> {
@@ -69,7 +69,7 @@ export declare function MapPersistenceErrors<TArgs extends unknown[], TEntity, T
69
69
  * replacement to express it in application terms.
70
70
  *
71
71
  * The canonical use is transient-failure classification with
72
- * {@link mapPersistenceError}, so that retry policies consume
72
+ * `mapPersistenceError`, so that retry policies consume
73
73
  * `TransientOperationError` rather than driver codes:
74
74
  *
75
75
  * ```typescript
@@ -24,7 +24,7 @@ export interface QueryRepositoryHydration<TResult> {
24
24
  * @typeParam TQuery - The query/options type accepted by {@link find}.
25
25
  * @typeParam TResult - The result type returned by {@link find}.
26
26
  *
27
- * @example Creating a query repository with @FromCache
27
+ * @example Creating a query repository with the FromCache decorator
28
28
  * ```typescript
29
29
  * @Injectable()
30
30
  * export class GetUserQueryRepository extends QueryRepository<GetUserQuery, User | null> {
@@ -9,7 +9,7 @@
9
9
  * @typeParam TQuery - The query/options type accepted by {@link find}.
10
10
  * @typeParam TResult - The result type returned by {@link find}.
11
11
  *
12
- * @example Creating a query repository with @FromCache
12
+ * @example Creating a query repository with the FromCache decorator
13
13
  * ```typescript
14
14
  * @Injectable()
15
15
  * export class GetUserQueryRepository extends QueryRepository<GetUserQuery, User | null> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cqrs-ddd/core",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Framework- and ORM-neutral DDD building blocks for TypeScript: aggregates and domain events, CQRS base classes and repository ports, and a revision-fenced repository cache, as separate entry points.",
5
5
  "author": "Aristotelis",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -13,7 +13,7 @@
13
13
  "url": "git+https://github.com/aristoteliss/nestjs-pipeline.git",
14
14
  "directory": "packages/ddd-core"
15
15
  },
16
- "homepage": "https://github.com/aristoteliss/nestjs-pipeline/tree/master/packages/ddd-core#readme",
16
+ "homepage": "https://aristoteliss.github.io/nestjs-pipeline/packages/cqrs-ddd/core/",
17
17
  "bugs": {
18
18
  "url": "https://github.com/aristoteliss/nestjs-pipeline/issues"
19
19
  },
@@ -61,8 +61,8 @@
61
61
  "access": "public"
62
62
  },
63
63
  "dependencies": {
64
- "@cqrs-ddd/safe-stringify": "^0.4.0",
65
- "@cqrs-ddd/uuidv7": "^0.4.0"
64
+ "@cqrs-ddd/safe-stringify": "^0.4.2",
65
+ "@cqrs-ddd/uuidv7": "^0.4.2"
66
66
  },
67
67
  "devDependencies": {
68
68
  "@vitest/coverage-v8": "^5.0.2",