@ddd-ts-kit/kernel 0.16.0 → 0.17.0
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.fr.md +2188 -0
- package/README.md +560 -31
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,13 +1,29 @@
|
|
|
1
|
+
**English** · [Français](README.fr.md)
|
|
2
|
+
|
|
1
3
|
# @ddd-ts-kit/kernel
|
|
2
4
|
|
|
3
5
|
The building blocks every context depends on, and nothing else: no framework, no ORM, no
|
|
4
|
-
logger, no dependency at all.
|
|
5
|
-
|
|
6
|
+
logger, no dependency at all. It is the only package of the kit `domain/` may import;
|
|
7
|
+
`application/` imports it too, and `@ddd-ts-kit/auth` next to it for permissions and policies.
|
|
6
8
|
|
|
7
9
|
```
|
|
8
10
|
npm i @ddd-ts-kit/kernel
|
|
9
11
|
```
|
|
10
12
|
|
|
13
|
+
Two entries: `@ddd-ts-kit/kernel` (the building blocks, the ports, the standard interfaces and
|
|
14
|
+
their doubles) and `@ddd-ts-kit/kernel/declarations` (the decorators with which a class says
|
|
15
|
+
what it is, see "Declarations").
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
The kernel says **what** a context needs (a `Clock`, a `UnitOfWork`, a `Logger`) and never
|
|
20
|
+
**how**: every port is an abstract class with abstract members only. Its implementations live
|
|
21
|
+
elsewhere: the doubles and in-process versions of the kernel itself for tests and a single
|
|
22
|
+
process, the adapter packages of the kit (`@ddd-ts-kit/pino`, `@ddd-ts-kit/redis`,
|
|
23
|
+
`@ddd-ts-kit/s3`, the ORM packages, ...) for production, and the `infrastructure/` of each
|
|
24
|
+
context for its own repositories and gateways. The platform chooses one per port when it
|
|
25
|
+
starts, so a business rule never changes with a library.
|
|
26
|
+
|
|
11
27
|
## What is inside
|
|
12
28
|
|
|
13
29
|
| Area | Exports |
|
|
@@ -17,26 +33,173 @@ npm i @ddd-ts-kit/kernel
|
|
|
17
33
|
| Buses | `Command`, `Query`, `CommandBus`, `QueryBus`, `BusMiddleware`, the in-process `InMemoryCommandBus` and `InMemoryQueryBus` (`register(type, handler, { context })` names the bounded context in `MessageInfo`), `unitOfWorkMiddleware` |
|
|
18
34
|
| Events | `IntegrationEvent`, `IntegrationEventPublisher`, `IntegrationEventSubscriber`, `EventBus` (both at once), `EventSubscribers` (the subscriber of each bounded context), `ProcessedEventStore`, `idempotent`, `InMemoryEventBus`, `DomainEventDispatcher`, `IntegrationEventCallback` and `DomainEventCallback` (the functions a subscriber and a dispatcher are given), `executionContextOfEvent`, `inEventScope`, `scopedPublisher`, `EventDelivery` (what a provider says of one delivery: attempt, last attempt, transport, source, consumer), `messagingSystemOf` |
|
|
19
35
|
| Domain events and the unit of work | `dispatchingOnSave` (the wrapper that makes a repository hand over what the aggregates it is given recorded), `announceDomainEvents`, `withinUnitOfWork` (what every `UnitOfWork.run` is built on: queue, dispatch before the commit, `after-commit` phase), `unitOfWorkStage` and `UnitOfWorkStage`, `DomainEventPhase`, `DomainEventSubscription`, `SaveAfterCommitError`, `AfterCommitFailure`, `reportAfterCommitFailures`, `InMemoryDomainEventDispatcher` |
|
|
20
|
-
|
|
|
36
|
+
| State machines | `defineStateMachine`, `StateMachine`, `TransitionError`, `InvalidStateMachineError`, `mermaidOfStateMachine` (see "State machines") |
|
|
37
|
+
| Actor | `Actor`, `AuthorizedCommand`, `AuthorizedQuery`, `ActorContext`, `systemActor` |
|
|
21
38
|
| Standard interfaces | `Session`, `ExecutionContext` and `ExecutionScope`, `Logger`, `Metrics`, `ErrorReporter`, `Cache`, `CacheInvalidation` and `CachePurger` (with `cacheTag`, `tenantCacheTags`, `CachePurgeRequest`, `PublishedCacheInvalidation`, `PurgingPublisher`, `RepeatedCachePurger`: see "Purging the HTTP caches"), `Lock`, `RateLimiter`, `Page` and `PageRequest`, `AuditStamp`, `TenantScoped`, `AuditTrail`, `AuditReader` and `AuditEntry` |
|
|
22
39
|
| Scheduled jobs | `JobScheduler`, `ScheduledJob`, `JobExecution`, `JobSchedule`, `JobOptions`, `JobDefinition`, `JobRun`, `JobDescription`, `parseJobSchedule`, `describeJobSchedule`, `jobPolicy`, `executionContextOfJob` |
|
|
40
|
+
| Background jobs | `JobQueue`, `BackgroundJob`, `BackgroundJobExecution`, `EnqueueOptions`, `QueuedJob`, `QueuedJobStatus`, `backgroundJobPolicy`, `retryDelayMs`, `executionContextOfBackgroundJob`, `whenCommitted` (see "JobQueue") |
|
|
41
|
+
| Process managers | `ProcessManager`, `ProcessDecision`, `ProcessRunner`, `ProcessStore`, `InMemoryProcessStore`, `UnreadableProcessStateError` (see "ProcessRunner and ProcessStore") |
|
|
42
|
+
| Files | `FileStorage`, `StoredFile`, `FileScanner`, `FileKeys`, `TenantFileKeys`, `FileStaging`, `FileUpload`, `fileUploadsMiddleware`, `FileInspection`, `FileError`, `InMemoryFileStorage`, `LocalFileStorage`, `PurgeStagedFiles` (see "FileStorage, StoredFile, FileScanner") |
|
|
43
|
+
| Tenancy | `tenantScopeOf`, `tenantReachOf`, `acrossTenants`, `tenantKey`, `tenantCacheKey`, `isTenantId`, `TenantDirectory`, `InMemoryTenantDirectory` (see "Tenancy") |
|
|
44
|
+
| Event sourcing | `EventSourcedAggregate`, `EventStore`, `defineStoredEvent`, `EventSerializer`, `EventSourcedRepository`, `SnapshotPolicy`, `personalData`, `PersonalDataCipher`, `CatchUpSubscription`, `EventStoreProjectionRebuild`, `InMemoryEventStore`, `PostgresEventStore` (see "Event sourcing") |
|
|
23
45
|
| Read side | `Criteria`, `defineCriteria`, `validateCriteria`, `scoped`, `planCriteria`, `evaluateCriteria`, `pageOfPlan`, `hydrate`, `ReadModelStore`, `stampOf`, `TableReadModelStore`, `ProjectionRebuild`, `InMemoryReadModelStore` (see "Criteria", "Hydration" and "Projections") |
|
|
24
46
|
| Persistence helpers | `optimisticUpdate`, `expectVersion` (the version a caller read, `If-Match` over HTTP, still the current one, else `PreconditionFailedError`: 412), `schemaNameOf`, `stampCreation`, `stampUpdate`, `tenantScopeOf`, `encodeCursor`, `decodeCursor` |
|
|
25
47
|
| Error reporting | `ErrorReporter`, `ErrorReport`, `errorReportOf`, `reportOnce`, `isUnexpectedError`, `errorReportingMiddleware`, `DeadLetterReports`, `reportProcessFailures`, `NoopErrorReporter` |
|
|
26
48
|
| Doubles | `FixedClock`, `SequentialIdGenerator`, `InMemoryUnitOfWork`, `FixedActorContext`, `FixedExecutionScope`, `InMemoryLogger`, `InMemoryMetrics`, `InMemoryErrorReporter`, `InMemoryCache`, `InMemoryCacheInvalidation`, `InMemoryCachePurger`, `InMemoryLock`, `InMemoryRateLimiter` |
|
|
27
|
-
| Declarations (`@ddd-ts-kit/kernel/declarations`) | `Requires`, `Public`, `CommandHandler`, `QueryHandler`, `IntegrationEventHandler`, `DomainEventHandler`, `Scheduled`, `Projection`, `On`, `Repository`, `Gateway`, `Adapter`, `Policy`, `injected`, `injectedDependencies`, `declarationOf`, `listDeclarations`, `Token`, `describeToken`, `tokenIdentity`, `portDefect` |
|
|
49
|
+
| Declarations (`@ddd-ts-kit/kernel/declarations`) | `Requires`, `Public`, `CommandHandler`, `QueryHandler`, `IntegrationEventHandler`, `DomainEventHandler`, `Scheduled`, `Background`, `Projection`, `On`, `applyingProjection`, `Repository`, `Gateway`, `Adapter`, `Policy`, `Edge` (for the decorators of a transport package, such as `@Controller`), `injected`, `injectedDependencies`, `declarationOf`, `listDeclarations`, `DeclarationError`, `Token`, `describeToken`, `tokenIdentity`, `portDefect` |
|
|
28
50
|
|
|
29
51
|
The rules these blocks serve are in `docs/ARCHITECTURE.md`.
|
|
30
52
|
|
|
53
|
+
## A first aggregate
|
|
54
|
+
|
|
55
|
+
The four building blocks of a model, in one file for the reading (a project gives each its own
|
|
56
|
+
file, and `ddd-ts-kit generate` writes them):
|
|
57
|
+
|
|
58
|
+
<!-- checked sample -->
|
|
59
|
+
```ts
|
|
60
|
+
import { AggregateRoot, ConceptError, Entity, ValueObject, type DomainEvent } from '@ddd-ts-kit/kernel';
|
|
61
|
+
|
|
62
|
+
// The refusals of the concept, each a static factory (see "Domain errors").
|
|
63
|
+
export class OrderError extends ConceptError {
|
|
64
|
+
static invalidQuantity(units: number) {
|
|
65
|
+
return OrderError.refusal('INVALID_QUANTITY', `${units} is not a positive whole quantity.`, { units });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
static alreadyPlaced(orderId: string) {
|
|
69
|
+
return OrderError.refusal('ORDER_ALREADY_PLACED', `Order ${orderId} is already placed.`, { orderId });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
static empty(orderId: string) {
|
|
73
|
+
return OrderError.refusal('ORDER_EMPTY', `Order ${orderId} has no line to place.`, { orderId });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// A value object: immutable, compared by value, valid once built.
|
|
78
|
+
export class Quantity extends ValueObject<{ readonly units: number }> {
|
|
79
|
+
private constructor(props: { readonly units: number }) {
|
|
80
|
+
super(props);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
static create(units: number): Quantity {
|
|
84
|
+
if (!Number.isInteger(units) || units <= 0) {
|
|
85
|
+
throw OrderError.invalidQuantity(units);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return new Quantity({ units });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get units(): number {
|
|
92
|
+
return this.props.units;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// An entity: known by its identity, reached only through its aggregate root.
|
|
97
|
+
export class OrderLine extends Entity {
|
|
98
|
+
constructor(
|
|
99
|
+
productId: string,
|
|
100
|
+
readonly quantity: Quantity,
|
|
101
|
+
) {
|
|
102
|
+
super(productId);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// A domain event: a fact of the past, named <context>.<aggregate>.<fact>.
|
|
107
|
+
export class OrderPlaced implements DomainEvent {
|
|
108
|
+
static readonly eventName = 'ordering.order.placed';
|
|
109
|
+
|
|
110
|
+
readonly name = OrderPlaced.eventName;
|
|
111
|
+
|
|
112
|
+
constructor(
|
|
113
|
+
readonly aggregateId: string,
|
|
114
|
+
readonly occurredAt: Date,
|
|
115
|
+
readonly lineCount: number,
|
|
116
|
+
) {}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// The aggregate root: the only way in, every rule checked by an intention method.
|
|
120
|
+
export class Order extends AggregateRoot {
|
|
121
|
+
private readonly lines: OrderLine[] = [];
|
|
122
|
+
private placed = false;
|
|
123
|
+
|
|
124
|
+
private constructor(id: string) {
|
|
125
|
+
super(id);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
static open(id: string): Order {
|
|
129
|
+
return new Order(id);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
add(productId: string, quantity: Quantity): void {
|
|
133
|
+
if (this.placed) {
|
|
134
|
+
throw OrderError.alreadyPlaced(this.id);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
this.lines.push(new OrderLine(productId, quantity));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
place(now: Date): void {
|
|
141
|
+
if (this.placed) {
|
|
142
|
+
throw OrderError.alreadyPlaced(this.id);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (this.lines.length === 0) {
|
|
146
|
+
throw OrderError.empty(this.id);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
this.placed = true;
|
|
150
|
+
this.record(new OrderPlaced(this.id, now, this.lines.length));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// What a spec of the aggregate checks:
|
|
155
|
+
const order = Order.open('o-1');
|
|
156
|
+
order.add('p-7', Quantity.create(2));
|
|
157
|
+
order.place(new Date('2026-01-05T09:00:00Z'));
|
|
158
|
+
|
|
159
|
+
order.pullEvents(); // [OrderPlaced { aggregateId: 'o-1', lineCount: 1, ... }]
|
|
160
|
+
Quantity.create(2).equals(Quantity.create(2)); // true: same value
|
|
161
|
+
new OrderLine('p-7', Quantity.create(1)).equals(new OrderLine('p-7', Quantity.create(5))); // true: same identity
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
| Block | What the kernel gives it |
|
|
165
|
+
|---|---|
|
|
166
|
+
| `Entity<Id>` | `id` and `equals`: two entities are equal when their class and their id are |
|
|
167
|
+
| `ValueObject<Props>` | frozen `props`, `equals` by value (dates by their time, lists and records deeply), `toJSON` |
|
|
168
|
+
| `AggregateRoot<Id>` | an entity with `version`, the optimistic concurrency token its repository adapter manages, `record(event)` for its methods and `pullEvents()`. The recorded events are not enumerable: spreading, comparing or serialising an aggregate never sees them |
|
|
169
|
+
| `DomainEvent` | an interface: `name`, `occurredAt`, `aggregateId` |
|
|
170
|
+
|
|
171
|
+
Instead of changing the state from outside, where every caller has to remember the rule:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
order.status = 'placed'; // nothing checks that the order has lines
|
|
175
|
+
events.push({ name: 'ordering.order.placed' }); // and nothing ties the fact to the change
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
write one intention method on the aggregate, which checks the rule and records the fact in the
|
|
179
|
+
same move:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
order.place(clock.now());
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`Result`, `ok`, `err` and `unwrap` are for a project that has value objects answer their
|
|
186
|
+
refusal instead of throwing it (`"stack.valueObjects": "result"`). Why each block exists:
|
|
187
|
+
[Aggregates](../../docs/concepts/aggregates.md) and
|
|
188
|
+
[Entities and value objects](../../docs/concepts/entities-and-value-objects.md).
|
|
189
|
+
|
|
31
190
|
## Domain errors
|
|
32
191
|
|
|
33
192
|
A business refusal is a `DomainError`: an answer the code planned for, known everywhere by its
|
|
34
193
|
`code`. A context has one error class per concept of its language, and each refusal is a static
|
|
35
194
|
factory of that class, named in the words of the business:
|
|
36
195
|
|
|
196
|
+
<!-- checked sample -->
|
|
37
197
|
```ts
|
|
38
198
|
import { ConceptError } from '@ddd-ts-kit/kernel';
|
|
39
199
|
|
|
200
|
+
declare const calendar: { readonly id: string };
|
|
201
|
+
declare const slot: { readonly startsAt: Date };
|
|
202
|
+
|
|
40
203
|
export class AppointmentError extends ConceptError {
|
|
41
204
|
static slotTaken(calendarId: string, startsAt: Date) {
|
|
42
205
|
return AppointmentError.refusal(
|
|
@@ -67,6 +230,22 @@ throw AppointmentError.slotTaken(calendar.id, slot.startsAt);
|
|
|
67
230
|
| `toJSON()` | `{ name, code, message }`, plus `facts` when some are exposed: never the stack, the cause or a private fact |
|
|
68
231
|
| `static is(error, code?)` | narrows what was caught to a refusal of this class, of this code when one is given |
|
|
69
232
|
|
|
233
|
+
Instead of a bare `Error`, which nothing downstream can tell from a bug:
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
throw new Error(`Slot ${startsAt.toISOString()} is taken`); // reported as unexpected, answered as a 500
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
write the refusal of the concept, which every layer knows by its code:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
throw AppointmentError.slotTaken(calendar.id, slot.startsAt); // a planned answer: a 4xx with code SLOT_TAKEN
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
The HTTP status of each code is chosen in the presentation layer, in one place; the error
|
|
246
|
+
logs, the spans and the audit trail record the `code`, and the error reporter leaves a
|
|
247
|
+
`DomainError` alone (the two exceptions are under "ErrorReporter").
|
|
248
|
+
|
|
70
249
|
The codes of a class are a closed vocabulary the compiler derives from its factories, so a
|
|
71
250
|
`switch` is exhaustive and each case knows its facts:
|
|
72
251
|
|
|
@@ -117,19 +296,84 @@ second. Both forms can live in one project.
|
|
|
117
296
|
|
|
118
297
|
## State machines
|
|
119
298
|
|
|
299
|
+
<!-- checked sample -->
|
|
120
300
|
```ts
|
|
301
|
+
import { AggregateRoot, ConceptError, defineStateMachine } from '@ddd-ts-kit/kernel';
|
|
302
|
+
|
|
303
|
+
// domain/vocabularies/parcel-status.vocabulary.ts
|
|
304
|
+
export const ParcelStatus = { Registered: 'registered', Shipped: 'shipped', Delivered: 'delivered' } as const;
|
|
305
|
+
export type ParcelStatus = (typeof ParcelStatus)[keyof typeof ParcelStatus];
|
|
306
|
+
|
|
307
|
+
// domain/errors/parcel.error.ts
|
|
308
|
+
export class ParcelError extends ConceptError {
|
|
309
|
+
static unpaid(parcelId: string) {
|
|
310
|
+
return ParcelError.refusal('PARCEL_UNPAID', `Parcel ${parcelId} is not paid yet.`, { parcelId });
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
static cannot(parcelId: string, from: ParcelStatus, transition: string) {
|
|
314
|
+
return ParcelError.refusal('PARCEL_TRANSITION_REFUSED', `Parcel ${parcelId} cannot ${transition} once ${from}.`, {
|
|
315
|
+
parcelId,
|
|
316
|
+
from,
|
|
317
|
+
transition,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// What the transitions are judged with: the aggregate hands it to `next`.
|
|
323
|
+
interface ParcelMoment {
|
|
324
|
+
readonly parcelId: string;
|
|
325
|
+
readonly paid: boolean;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// domain/state-machines/parcel.state-machine.ts
|
|
121
329
|
export const parcelLifecycle = defineStateMachine({
|
|
122
330
|
states: Object.values(ParcelStatus),
|
|
123
331
|
initial: [ParcelStatus.Registered],
|
|
124
332
|
transitions: {
|
|
125
|
-
ship: {
|
|
333
|
+
ship: {
|
|
334
|
+
from: [ParcelStatus.Registered],
|
|
335
|
+
to: ParcelStatus.Shipped,
|
|
336
|
+
guard: ({ parcelId, paid }: ParcelMoment) => (paid ? undefined : ParcelError.unpaid(parcelId)),
|
|
337
|
+
},
|
|
126
338
|
reroute: { from: [ParcelStatus.Shipped] },
|
|
127
339
|
deliver: { from: [ParcelStatus.Shipped], to: ParcelStatus.Delivered },
|
|
128
340
|
},
|
|
129
|
-
refused: ({ from, transition }) => ParcelError.cannot(from, transition),
|
|
341
|
+
refused: ({ from, transition }, { parcelId }: ParcelMoment) => ParcelError.cannot(parcelId, from, transition),
|
|
130
342
|
});
|
|
131
343
|
|
|
132
|
-
|
|
344
|
+
// domain/aggregates/parcel.aggregate.ts: the aggregate asks the machine, never tests its status by hand
|
|
345
|
+
export class Parcel extends AggregateRoot {
|
|
346
|
+
private status: ParcelStatus = parcelLifecycle.start(ParcelStatus.Registered);
|
|
347
|
+
|
|
348
|
+
private constructor(
|
|
349
|
+
id: string,
|
|
350
|
+
private readonly paid: boolean,
|
|
351
|
+
) {
|
|
352
|
+
super(id);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
static register(id: string, paid: boolean): Parcel {
|
|
356
|
+
return new Parcel(id, paid);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
ship(): void {
|
|
360
|
+
this.status = parcelLifecycle.next(this.status, 'ship', this.moment());
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
deliver(): void {
|
|
364
|
+
this.status = parcelLifecycle.next(this.status, 'deliver', this.moment());
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private moment(): ParcelMoment {
|
|
368
|
+
return { parcelId: this.id, paid: this.paid };
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
Parcel.register('p-1', false).ship(); // throws PARCEL_UNPAID: the guard refused
|
|
373
|
+
Parcel.register('p-2', true).deliver(); // throws PARCEL_TRANSITION_REFUSED: registered cannot deliver
|
|
374
|
+
|
|
375
|
+
parcelLifecycle.allowedFrom(ParcelStatus.Shipped); // ['reroute', 'deliver']
|
|
376
|
+
parcelLifecycle.isFinal(ParcelStatus.Delivered); // true
|
|
133
377
|
```
|
|
134
378
|
|
|
135
379
|
The lifecycle of an aggregate, in `domain/state-machines/<aggregate>.state-machine.ts`.
|
|
@@ -146,6 +390,8 @@ loads. Why, and the rule that holds the aggregate to it:
|
|
|
146
390
|
|
|
147
391
|
An effect of a domain event exists only if the state change that recorded it is committed.
|
|
148
392
|
|
|
393
|
+

|
|
394
|
+
|
|
149
395
|
An aggregate records its events; nothing in a use case hands them over. A repository wrapped
|
|
150
396
|
by `dispatchingOnSave(repository, () => dispatcher)` pulls them itself, once a method that was
|
|
151
397
|
handed the aggregate has resolved:
|
|
@@ -174,6 +420,73 @@ failures, wrapper order) is in the README of that package. In short:
|
|
|
174
420
|
- Outside any unit of work the save dispatches before it resolves, `before-commit` handlers
|
|
175
421
|
then `after-commit` ones.
|
|
176
422
|
|
|
423
|
+
The whole timeline, with the doubles of the kernel and nothing else, as a spec would set it up:
|
|
424
|
+
|
|
425
|
+
<!-- checked sample -->
|
|
426
|
+
```ts
|
|
427
|
+
import {
|
|
428
|
+
AggregateRoot,
|
|
429
|
+
InMemoryDomainEventDispatcher,
|
|
430
|
+
InMemoryUnitOfWork,
|
|
431
|
+
dispatchingOnSave,
|
|
432
|
+
type DomainEvent,
|
|
433
|
+
} from '@ddd-ts-kit/kernel';
|
|
434
|
+
|
|
435
|
+
class CartOpened implements DomainEvent {
|
|
436
|
+
static readonly eventName = 'shop.cart.opened';
|
|
437
|
+
|
|
438
|
+
readonly name = CartOpened.eventName;
|
|
439
|
+
|
|
440
|
+
constructor(
|
|
441
|
+
readonly aggregateId: string,
|
|
442
|
+
readonly occurredAt: Date,
|
|
443
|
+
) {}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
class Cart extends AggregateRoot {
|
|
447
|
+
static open(id: string, now: Date): Cart {
|
|
448
|
+
const cart = new Cart(id);
|
|
449
|
+
|
|
450
|
+
cart.record(new CartOpened(id, now));
|
|
451
|
+
|
|
452
|
+
return cart;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
class InMemoryCarts {
|
|
457
|
+
readonly saved: string[] = [];
|
|
458
|
+
|
|
459
|
+
async save(cart: Cart): Promise<void> {
|
|
460
|
+
this.saved.push(cart.id);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const journal: string[] = [];
|
|
465
|
+
const dispatcher = new InMemoryDomainEventDispatcher();
|
|
466
|
+
const carts = dispatchingOnSave(new InMemoryCarts(), () => dispatcher);
|
|
467
|
+
const unitOfWork = new InMemoryUnitOfWork();
|
|
468
|
+
|
|
469
|
+
dispatcher.on(CartOpened.eventName, async (event) => {
|
|
470
|
+
journal.push(`before-commit ${event.aggregateId} sees ${carts.saved.join(' and ')}`);
|
|
471
|
+
});
|
|
472
|
+
dispatcher.on(CartOpened.eventName, async (event) => void journal.push(`after-commit ${event.aggregateId}`), {
|
|
473
|
+
phase: 'after-commit',
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
const now = new Date('2026-01-05T09:00:00Z');
|
|
477
|
+
|
|
478
|
+
await unitOfWork.run(async () => {
|
|
479
|
+
await carts.save(Cart.open('c1', now));
|
|
480
|
+
journal.push('saved c1');
|
|
481
|
+
await carts.save(Cart.open('c2', now));
|
|
482
|
+
journal.push('saved c2');
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
// journal: saved c1, saved c2,
|
|
486
|
+
// before-commit c1 sees c1 and c2, before-commit c2 sees c1 and c2,
|
|
487
|
+
// after-commit c1, after-commit c2
|
|
488
|
+
```
|
|
489
|
+
|
|
177
490
|
`pullEvents()` stays public for this wrapper and for the specs of an aggregate; a use case and
|
|
178
491
|
a repository adapter never call it. An aggregate is recognised by what it does (it has
|
|
179
492
|
`pullEvents`), so a context compiled against another copy of the kernel is followed too.
|
|
@@ -317,6 +630,43 @@ private or protected member. A port may extend another port. An adapter `impleme
|
|
|
317
630
|
and never `extends` it. The type stays structural, so a fake, an in-memory class or a plain
|
|
318
631
|
object literal stands for a port without ceremony.
|
|
319
632
|
|
|
633
|
+
<!-- checked sample -->
|
|
634
|
+
```ts
|
|
635
|
+
import { Clock } from '@ddd-ts-kit/kernel';
|
|
636
|
+
import { Adapter } from '@ddd-ts-kit/kernel/declarations';
|
|
637
|
+
|
|
638
|
+
interface Money {
|
|
639
|
+
readonly amount: string;
|
|
640
|
+
readonly currency: string;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
interface PaymentReceipt {
|
|
644
|
+
readonly reference: string;
|
|
645
|
+
readonly paidAt: Date;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// application/ports/payment-gateway.port.ts: abstract members only
|
|
649
|
+
export abstract class PaymentGateway {
|
|
650
|
+
abstract charge(orderId: string, amount: Money): Promise<PaymentReceipt>;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// infrastructure/external/http-payment-gateway.adapter.ts: implements its port, never extends it
|
|
654
|
+
@Adapter(PaymentGateway, { kind: 'external' })
|
|
655
|
+
export class HttpPaymentGateway implements PaymentGateway {
|
|
656
|
+
constructor(private readonly clock: Clock) {}
|
|
657
|
+
|
|
658
|
+
async charge(orderId: string, amount: Money): Promise<PaymentReceipt> {
|
|
659
|
+
// the call to the payment provider goes here
|
|
660
|
+
return { reference: `${orderId}:${amount.amount}:${amount.currency}`, paidAt: this.clock.now() };
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// test/fakes: a plain object is a PaymentGateway, since the type is structural
|
|
665
|
+
export const acceptingGateway: PaymentGateway = {
|
|
666
|
+
charge: async (orderId) => ({ reference: `fake-${orderId}`, paidAt: new Date('2026-01-05T09:00:00Z') }),
|
|
667
|
+
};
|
|
668
|
+
```
|
|
669
|
+
|
|
320
670
|
**`Repository<A, Id>`** is the contract every repository shares (`findById`, `save`), as an
|
|
321
671
|
abstract class. The repository port of an aggregate extends it and adds its own finders, as
|
|
322
672
|
`OrderRepository` above; the adapter implements that port.
|
|
@@ -341,7 +691,20 @@ builder.bind(Database).toValue({ client: knex });
|
|
|
341
691
|
builder.bind(PaymentSettings).toValue({ apiKey: configuration.paymentApiKey });
|
|
342
692
|
```
|
|
343
693
|
|
|
344
|
-
That is the one way: no string token, no symbol token, no helper.
|
|
694
|
+
That is the one way: no string token, no symbol token, no helper. Instead of a token next to
|
|
695
|
+
the type, two names to keep in step:
|
|
696
|
+
|
|
697
|
+
```ts
|
|
698
|
+
export const PAYMENT_GATEWAY = Symbol('PaymentGateway');
|
|
699
|
+
|
|
700
|
+
constructor(@Inject(PAYMENT_GATEWAY) private readonly payments: PaymentGateway) {}
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
write the type alone, which is the token:
|
|
704
|
+
|
|
705
|
+
```ts
|
|
706
|
+
constructor(private readonly payments: PaymentGateway) {}
|
|
707
|
+
```
|
|
345
708
|
|
|
346
709
|
**Identity across copies.** A class is its own identity, and two copies of a package loaded in
|
|
347
710
|
one process (a duplicated install, a bundle next to `node_modules`) hold two classes. A port
|
|
@@ -389,17 +752,46 @@ constructor parameter is typed by one class, its token, and `ddd-ts-kit docs` re
|
|
|
389
752
|
signatures from the sources into the generated file of the context, which registers them with
|
|
390
753
|
`injected`:
|
|
391
754
|
|
|
755
|
+
<!-- checked sample -->
|
|
392
756
|
```ts
|
|
757
|
+
import { AggregateRoot, Clock, Command, Repository } from '@ddd-ts-kit/kernel';
|
|
758
|
+
import { CommandHandler, injected, injectedDependencies } from '@ddd-ts-kit/kernel/declarations';
|
|
759
|
+
|
|
760
|
+
declare class Order extends AggregateRoot {
|
|
761
|
+
static place(id: string, customerId: string, now: Date): Order;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
export abstract class OrderRepository extends Repository<Order> {}
|
|
765
|
+
|
|
766
|
+
export class PlaceOrder extends Command<string> {
|
|
767
|
+
constructor(
|
|
768
|
+
readonly orderId: string,
|
|
769
|
+
readonly customerId: string,
|
|
770
|
+
) {
|
|
771
|
+
super();
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
393
775
|
@CommandHandler(PlaceOrder)
|
|
394
776
|
export class PlaceOrderHandler implements CommandHandler<PlaceOrder> {
|
|
395
777
|
constructor(
|
|
396
778
|
private readonly orders: OrderRepository,
|
|
397
779
|
private readonly clock: Clock,
|
|
398
780
|
) {}
|
|
781
|
+
|
|
782
|
+
async execute(command: PlaceOrder): Promise<string> {
|
|
783
|
+
const order = Order.place(command.orderId, command.customerId, this.clock.now());
|
|
784
|
+
|
|
785
|
+
await this.orders.save(order);
|
|
786
|
+
|
|
787
|
+
return order.id;
|
|
788
|
+
}
|
|
399
789
|
}
|
|
400
790
|
|
|
401
791
|
// contexts/ordering/ordering.declarations.ts, generated
|
|
402
792
|
injected(PlaceOrderHandler, [OrderRepository, Clock]);
|
|
793
|
+
|
|
794
|
+
injectedDependencies(PlaceOrderHandler); // [OrderRepository, Clock]: what a container builds the handler with
|
|
403
795
|
```
|
|
404
796
|
|
|
405
797
|
`injected(Class, [Tokens])` records one token per constructor parameter, in order, in a
|
|
@@ -459,9 +851,9 @@ left alone.
|
|
|
459
851
|
the decorator only says who may send it. `@Requires` is refused by the compiler on a message
|
|
460
852
|
without an actor. `audited` lists the fields an audit trail may record (a name, or
|
|
461
853
|
`{ field, masked: true }`), as plain data; the compiler checks that the message has them.
|
|
462
|
-
- **Dependencies are
|
|
463
|
-
|
|
464
|
-
no reflection.
|
|
854
|
+
- **Dependencies are said by the constructor**, as above. A list written as the last argument
|
|
855
|
+
of a decorator, the form of 0.1, names one port per parameter and is checked against the
|
|
856
|
+
constructor. There is no parameter decorator and no reflection.
|
|
465
857
|
- **The role is checked too**: a handler of another message or of another result, an event
|
|
466
858
|
handler of another payload, a job without `run` are refused by the compiler.
|
|
467
859
|
- **Options of a repository, a gateway and an adapter**: `transient: true` (one instance per
|
|
@@ -619,8 +1011,10 @@ what it received as a principal.
|
|
|
619
1011
|
|
|
620
1012
|
What every unit of work carries, whatever started it: `correlationId`, `causationId?`, `actor`,
|
|
621
1013
|
`session?`, `tenantId?`, `elevation?` (platform staff reading over tenants, see "Tenancy"),
|
|
622
|
-
`locale?`, `deadline?`, `scheduledAt?` (for a scheduled job, the instant it was due), `origin`
|
|
623
|
-
|
|
1014
|
+
`locale?`, `deadline?`, `scheduledAt?` (for a scheduled job, the instant it was due), `origin`
|
|
1015
|
+
(`http`, `event`, `schedule`, `queue` for a background job, `cli`, or a string of the project)
|
|
1016
|
+
and `extensions`. `executionContext(init)` builds one and takes the tenant of the actor;
|
|
1017
|
+
`withActor(context, actor)` is the same work seen as another actor.
|
|
624
1018
|
|
|
625
1019
|
`ExecutionScope` (`current()`, `require()`, `run(context, work)`) gives the context of the work
|
|
626
1020
|
in progress to code that is not handed it. The boundary sets it once:
|
|
@@ -635,9 +1029,51 @@ scope.run(executionContext({ correlationId, actor, session, origin: 'http' }), (
|
|
|
635
1029
|
const row = { ...toRow(order), ...stampCreation(scope, clock), ...tenantScopeOf(scope) };
|
|
636
1030
|
```
|
|
637
1031
|
|
|
1032
|
+
Both ends, with the implementation that follows the asynchronous call chain:
|
|
1033
|
+
|
|
1034
|
+
<!-- checked sample -->
|
|
1035
|
+
```ts
|
|
1036
|
+
import {
|
|
1037
|
+
AsyncLocalStorageExecutionScope,
|
|
1038
|
+
FixedClock,
|
|
1039
|
+
executionContext,
|
|
1040
|
+
stampCreation,
|
|
1041
|
+
tenantScopeOf,
|
|
1042
|
+
type Actor,
|
|
1043
|
+
} from '@ddd-ts-kit/kernel';
|
|
1044
|
+
|
|
1045
|
+
const scope = new AsyncLocalStorageExecutionScope();
|
|
1046
|
+
const clock = new FixedClock(new Date('2026-01-05T09:00:00Z'));
|
|
1047
|
+
const actor: Actor = { id: 'u-42', type: 'user', tenantId: 'acme', roles: ['agent'], attributes: {} };
|
|
1048
|
+
|
|
1049
|
+
// the boundary: set once for the request
|
|
1050
|
+
await scope.run(executionContext({ correlationId: 'req-7f3a', actor, origin: 'http' }), async () => {
|
|
1051
|
+
// ...the command goes through the bus to its handler, which saves; in the repository adapter:
|
|
1052
|
+
const row = { id: 'o-1', ...stampCreation(scope, clock), ...tenantScopeOf(scope) };
|
|
1053
|
+
// { id: 'o-1', createdAt, createdBy: 'u-42', updatedAt, updatedBy: 'u-42', tenantId: 'acme' }
|
|
1054
|
+
return row;
|
|
1055
|
+
});
|
|
1056
|
+
```
|
|
1057
|
+
|
|
638
1058
|
Use cases and the domain never read the scope: they receive the actor, and anything else they
|
|
639
1059
|
need, in the command or query (`authz/actor-explicit`). The scope is for loggers, audit columns,
|
|
640
|
-
tenant scoping and outgoing headers.
|
|
1060
|
+
tenant scoping and outgoing headers. Instead of a handler that asks the scope who acts, a
|
|
1061
|
+
dependency its signature hides:
|
|
1062
|
+
|
|
1063
|
+
```ts
|
|
1064
|
+
const actor = this.scope.require().actor;
|
|
1065
|
+
```
|
|
1066
|
+
|
|
1067
|
+
write a command that carries its actor, the first argument of an `AuthorizedCommand`, and read
|
|
1068
|
+
`command.actor` in the handler:
|
|
1069
|
+
|
|
1070
|
+
```ts
|
|
1071
|
+
export class CancelOrder extends AuthorizedCommand {
|
|
1072
|
+
constructor(actor: Actor, readonly orderId: string) {
|
|
1073
|
+
super(actor);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
```
|
|
641
1077
|
|
|
642
1078
|
A consumed event opens its own context: `executionContextOfEvent(event, { consumer })` has
|
|
643
1079
|
origin `event`, the correlation of the event (its id when it names none), the event as
|
|
@@ -668,7 +1104,7 @@ log.
|
|
|
668
1104
|
|
|
669
1105
|
**Errors are log values.** `LogValue` admits an `Error`, so
|
|
670
1106
|
`logger.error('payment failed', { error })` compiles as it is, and a project may name the key
|
|
671
|
-
once (`interface LogFields { error?: Error }`, see "
|
|
1107
|
+
once (`interface LogFields { error?: Error }`, see "How to extend"). An `Error` directly under a
|
|
672
1108
|
key of the fields is written by every logger as `describeError(error)` describes it, an
|
|
673
1109
|
`ErrorDescription`:
|
|
674
1110
|
|
|
@@ -752,11 +1188,25 @@ and tenant ids come from the execution context, never threaded by hand.
|
|
|
752
1188
|
|
|
753
1189
|
### Cache
|
|
754
1190
|
|
|
1191
|
+
<!-- checked sample -->
|
|
755
1192
|
```ts
|
|
1193
|
+
import { FixedClock, InMemoryCache, cacheKey } from '@ddd-ts-kit/kernel';
|
|
1194
|
+
|
|
1195
|
+
interface Quote {
|
|
1196
|
+
readonly pair: string;
|
|
1197
|
+
readonly rate: string;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
756
1200
|
const quoteKey = (pair: string) => cacheKey<Quote>('quote', pair);
|
|
757
1201
|
|
|
758
|
-
|
|
759
|
-
const
|
|
1202
|
+
const clock = new FixedClock(new Date('2026-01-05T09:00:00Z'));
|
|
1203
|
+
const cache = new InMemoryCache(clock, { maxEntries: 500 });
|
|
1204
|
+
|
|
1205
|
+
await cache.set(quoteKey('EUR-USD'), { pair: 'EUR-USD', rate: '1.0842' }, { ttlMs: 60_000 });
|
|
1206
|
+
const hit: Quote | undefined = await cache.get(quoteKey('EUR-USD')); // the quote, typed by its key
|
|
1207
|
+
|
|
1208
|
+
clock.advance(60_000);
|
|
1209
|
+
await cache.get(quoteKey('EUR-USD')); // undefined: expired, by the clock
|
|
760
1210
|
```
|
|
761
1211
|
|
|
762
1212
|
The key carries the type of its value. `InMemoryCache(clock, { maxEntries? })` expires by the
|
|
@@ -789,15 +1239,24 @@ and reached the cache after the first purge; the second purge is best effort, re
|
|
|
789
1239
|
|
|
790
1240
|
### Lock
|
|
791
1241
|
|
|
1242
|
+
<!-- checked sample -->
|
|
792
1243
|
```ts
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
await
|
|
799
|
-
|
|
800
|
-
|
|
1244
|
+
import type { Lock } from '@ddd-ts-kit/kernel';
|
|
1245
|
+
|
|
1246
|
+
declare function exportEverything(): Promise<void>;
|
|
1247
|
+
|
|
1248
|
+
export async function nightlyExport(lock: Lock): Promise<void> {
|
|
1249
|
+
const handle = await lock.acquire('nightly-export', { ttlMs: 60_000, waitMs: 0 });
|
|
1250
|
+
|
|
1251
|
+
if (handle === undefined) { // somebody else holds the key
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
try {
|
|
1256
|
+
await exportEverything();
|
|
1257
|
+
} finally {
|
|
1258
|
+
await handle.release();
|
|
1259
|
+
}
|
|
801
1260
|
}
|
|
802
1261
|
```
|
|
803
1262
|
|
|
@@ -877,8 +1336,9 @@ Connectors: `InMemoryFileStorage` for the tests (`keys()` lists what it holds) a
|
|
|
877
1336
|
their signed links point at the application, which answers them with `signedFileRoutes` of
|
|
878
1337
|
`@ddd-ts-kit/http`. The object store connector is `@ddd-ts-kit/s3`. Each passes
|
|
879
1338
|
`fileStorageContract` of `@ddd-ts-kit/testing/contracts`. Background import and export (row by
|
|
880
|
-
row validation, an error report, resumption)
|
|
881
|
-
|
|
1339
|
+
row validation, an error report, resumption) is a design built on these ports and the job queue
|
|
1340
|
+
(see "JobQueue"), not a feature of this version:
|
|
1341
|
+
[File import and export](../../docs/concepts/file-import-export.md).
|
|
882
1342
|
|
|
883
1343
|
### JobScheduler
|
|
884
1344
|
|
|
@@ -964,10 +1424,24 @@ the instances as JSON, for tests and one process. The runner is `StoredProcessRu
|
|
|
964
1424
|
|
|
965
1425
|
### RateLimiter
|
|
966
1426
|
|
|
1427
|
+
<!-- checked sample -->
|
|
967
1428
|
```ts
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
1429
|
+
import { ConceptError, type RateLimiter } from '@ddd-ts-kit/kernel';
|
|
1430
|
+
|
|
1431
|
+
export class PasswordResetError extends ConceptError {
|
|
1432
|
+
static tooManyAttempts(retryAfterMs: number) {
|
|
1433
|
+
return PasswordResetError.refusal('TOO_MANY_RESET_ATTEMPTS', 'Too many password resets: try again later.', {
|
|
1434
|
+
retryAfterMs,
|
|
1435
|
+
}).exposing('retryAfterMs');
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
export async function allowReset(limiter: RateLimiter, accountId: string): Promise<void> {
|
|
1440
|
+
const decision = await limiter.consume(`password-reset:${accountId}`, { limit: 3, windowMs: 3_600_000 });
|
|
1441
|
+
|
|
1442
|
+
if (!decision.allowed) {
|
|
1443
|
+
throw PasswordResetError.tooManyAttempts(decision.retryAfterMs);
|
|
1444
|
+
}
|
|
971
1445
|
}
|
|
972
1446
|
```
|
|
973
1447
|
|
|
@@ -1007,10 +1481,15 @@ case or a guard), then calls `acrossTenants`. A trail that fails to record it re
|
|
|
1007
1481
|
|
|
1008
1482
|
One shape for every search, in two variants:
|
|
1009
1483
|
|
|
1484
|
+
<!-- checked sample -->
|
|
1010
1485
|
```ts
|
|
1486
|
+
import { cursorPage, offsetPage } from '@ddd-ts-kit/kernel';
|
|
1487
|
+
|
|
1488
|
+
declare const cursor: string; // the nextCursor of the previous page
|
|
1489
|
+
|
|
1011
1490
|
offsetPage({ offset: 40, limit: 20, sort: [{ field: 'placedAt', direction: 'desc' }] });
|
|
1012
1491
|
cursorPage({ cursor, limit: 50 });
|
|
1013
|
-
// both
|
|
1492
|
+
// both build a PageRequest; the search answers a Page<T>: { items, total?, nextCursor? }
|
|
1014
1493
|
```
|
|
1015
1494
|
|
|
1016
1495
|
A cursor is opaque to the client and plain to the reader: `encodeCursor(position)` writes the
|
|
@@ -1081,6 +1560,7 @@ A read of a read model, described once for every search: filters, a sort, a page
|
|
|
1081
1560
|
knows field names and nothing of a store. It is not a specification: a specification is a
|
|
1082
1561
|
business predicate on an aggregate and lives in the domain; a criteria describes a read.
|
|
1083
1562
|
|
|
1563
|
+
<!-- checked sample -->
|
|
1084
1564
|
```ts
|
|
1085
1565
|
// contexts/scheduling/application/ports/appointment-list.port.ts
|
|
1086
1566
|
import { ReadModelStore, defineCriteria } from '@ddd-ts-kit/kernel';
|
|
@@ -1125,6 +1605,11 @@ const scope = await this.access.scope(query.actor, permissions['appointment.read
|
|
|
1125
1605
|
return this.appointments.search(scoped(criteria, scope, { ids: 'id', filter: { tenantId: 'tenantId' } }));
|
|
1126
1606
|
```
|
|
1127
1607
|
|
|
1608
|
+
From the handler to the store, a criteria is checked twice, and the scope of the actor travels
|
|
1609
|
+
with it:
|
|
1610
|
+
|
|
1611
|
+

|
|
1612
|
+
|
|
1128
1613
|
**Checked by the compiler.** `where` takes a field of the row, an operator that applies to
|
|
1129
1614
|
what the field holds, and a value of its type: `where('seats', 'contains', '2')`, an order on
|
|
1130
1615
|
a boolean, `isNull` on a field that is never null, a value outside a union of literals and a
|
|
@@ -1200,6 +1685,50 @@ scope need no operator in the definition: the read port chose them, not the call
|
|
|
1200
1685
|
is the shape `AccessScope` of `@ddd-ts-kit/auth`, named `ReadScope` here so that the kernel
|
|
1201
1686
|
depends on no authorization model.
|
|
1202
1687
|
|
|
1688
|
+
What that means on four rows, run in memory with the reference semantics:
|
|
1689
|
+
|
|
1690
|
+
<!-- checked sample -->
|
|
1691
|
+
```ts
|
|
1692
|
+
import { Criteria, defineCriteria, evaluateCriteria, scoped } from '@ddd-ts-kit/kernel';
|
|
1693
|
+
|
|
1694
|
+
interface BookingRow {
|
|
1695
|
+
readonly id: string;
|
|
1696
|
+
readonly room: string | null;
|
|
1697
|
+
readonly tenantId: string;
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
const bookings = defineCriteria<BookingRow>({
|
|
1701
|
+
fields: {
|
|
1702
|
+
id: { type: 'string' },
|
|
1703
|
+
room: { type: 'string', filter: ['eq'], nullable: true },
|
|
1704
|
+
tenantId: { type: 'string' },
|
|
1705
|
+
},
|
|
1706
|
+
defaultSort: [{ field: 'id', direction: 'asc' }],
|
|
1707
|
+
tieBreaker: 'id',
|
|
1708
|
+
});
|
|
1709
|
+
|
|
1710
|
+
const rows: BookingRow[] = [
|
|
1711
|
+
{ id: 'a-1', room: 'A', tenantId: 'acme' },
|
|
1712
|
+
{ id: 'a-2', room: 'B', tenantId: 'acme' },
|
|
1713
|
+
{ id: 'a-3', room: null, tenantId: 'acme' },
|
|
1714
|
+
{ id: 'g-1', room: 'A', tenantId: 'globex' },
|
|
1715
|
+
];
|
|
1716
|
+
|
|
1717
|
+
// `not` keeps the row without a room, where SQL alone would drop it
|
|
1718
|
+
evaluateCriteria(bookings, rows, Criteria.of<BookingRow>().not((all) => all.where('room', 'eq', 'B')));
|
|
1719
|
+
// items: a-1, a-3, g-1
|
|
1720
|
+
|
|
1721
|
+
// an `or` the caller writes never widens the scope: the scope is joined to it by AND
|
|
1722
|
+
const anyRoom = Criteria.of<BookingRow>().or((any) => any.where('room', 'eq', 'A').where('room', 'eq', 'B'));
|
|
1723
|
+
const acmeOnly = { kind: 'filter', filter: { tenantId: 'acme' } } as const;
|
|
1724
|
+
evaluateCriteria(bookings, rows, scoped(anyRoom, acmeOnly, { filter: { tenantId: 'tenantId' } }));
|
|
1725
|
+
// items: a-1, a-2; g-1 belongs to another tenant
|
|
1726
|
+
|
|
1727
|
+
// the caller cannot filter on tenantId itself: the field declares no operator
|
|
1728
|
+
evaluateCriteria(bookings, rows, Criteria.of<BookingRow>().where('tenantId', 'eq', 'globex'));
|
|
1729
|
+
// throws InvalidCriteriaError: filter.tenantId (operator_not_allowed)
|
|
1730
|
+
```
|
|
1731
|
+
|
|
1203
1732
|
### For a store
|
|
1204
1733
|
|
|
1205
1734
|
`planCriteria` answers a `CriteriaPlan`, plain data a translator renders and nothing else: the
|