ddd-ts-kit 0.7.0 → 0.8.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.
Files changed (99) hide show
  1. package/README.md +9 -4
  2. package/dist/check/catalogue/architecture-rules.d.ts.map +1 -1
  3. package/dist/check/catalogue/architecture-rules.js +2 -0
  4. package/dist/check/catalogue/architecture-rules.js.map +1 -1
  5. package/dist/check/explain/rule-docs.d.ts.map +1 -1
  6. package/dist/check/explain/rule-docs.js +2 -0
  7. package/dist/check/explain/rule-docs.js.map +1 -1
  8. package/dist/check/explain/tenancy-docs.d.ts +3 -0
  9. package/dist/check/explain/tenancy-docs.d.ts.map +1 -0
  10. package/dist/check/explain/tenancy-docs.js +15 -0
  11. package/dist/check/explain/tenancy-docs.js.map +1 -0
  12. package/dist/check/fixtures/fixtures.d.ts.map +1 -1
  13. package/dist/check/fixtures/fixtures.js +2 -0
  14. package/dist/check/fixtures/fixtures.js.map +1 -1
  15. package/dist/check/fixtures/tenancy-fixtures.d.ts +3 -0
  16. package/dist/check/fixtures/tenancy-fixtures.d.ts.map +1 -0
  17. package/dist/check/fixtures/tenancy-fixtures.js +136 -0
  18. package/dist/check/fixtures/tenancy-fixtures.js.map +1 -0
  19. package/dist/check/rules/tenancy-scoped-statement.d.ts +3 -0
  20. package/dist/check/rules/tenancy-scoped-statement.d.ts.map +1 -0
  21. package/dist/check/rules/tenancy-scoped-statement.js +37 -0
  22. package/dist/check/rules/tenancy-scoped-statement.js.map +1 -0
  23. package/dist/check/tenancy/balanced-arguments.d.ts +3 -0
  24. package/dist/check/tenancy/balanced-arguments.d.ts.map +1 -0
  25. package/dist/check/tenancy/balanced-arguments.js +13 -0
  26. package/dist/check/tenancy/balanced-arguments.js.map +1 -0
  27. package/dist/check/tenancy/declared-with.d.ts +11 -0
  28. package/dist/check/tenancy/declared-with.d.ts.map +1 -0
  29. package/dist/check/tenancy/declared-with.js +13 -0
  30. package/dist/check/tenancy/declared-with.js.map +1 -0
  31. package/dist/check/tenancy/drizzle-unscoped.d.ts +7 -0
  32. package/dist/check/tenancy/drizzle-unscoped.d.ts.map +1 -0
  33. package/dist/check/tenancy/drizzle-unscoped.js +35 -0
  34. package/dist/check/tenancy/drizzle-unscoped.js.map +1 -0
  35. package/dist/check/tenancy/executor-uses.d.ts +11 -0
  36. package/dist/check/tenancy/executor-uses.d.ts.map +1 -0
  37. package/dist/check/tenancy/executor-uses.js +14 -0
  38. package/dist/check/tenancy/executor-uses.js.map +1 -0
  39. package/dist/check/tenancy/knex-unscoped.d.ts +7 -0
  40. package/dist/check/tenancy/knex-unscoped.d.ts.map +1 -0
  41. package/dist/check/tenancy/knex-unscoped.js +19 -0
  42. package/dist/check/tenancy/knex-unscoped.js.map +1 -0
  43. package/dist/check/tenancy/unscoped-read-models.d.ts +4 -0
  44. package/dist/check/tenancy/unscoped-read-models.d.ts.map +1 -0
  45. package/dist/check/tenancy/unscoped-read-models.js +15 -0
  46. package/dist/check/tenancy/unscoped-read-models.js.map +1 -0
  47. package/dist/commands/init.d.ts.map +1 -1
  48. package/dist/commands/init.js +1 -0
  49. package/dist/commands/init.js.map +1 -1
  50. package/dist/config/index.d.ts +1 -1
  51. package/dist/config/index.d.ts.map +1 -1
  52. package/dist/config/index.js +1 -1
  53. package/dist/config/index.js.map +1 -1
  54. package/dist/config/parse-stack.d.ts.map +1 -1
  55. package/dist/config/parse-stack.js +2 -1
  56. package/dist/config/parse-stack.js.map +1 -1
  57. package/dist/config/stack.d.ts +10 -0
  58. package/dist/config/stack.d.ts.map +1 -1
  59. package/dist/config/stack.js +7 -0
  60. package/dist/config/stack.js.map +1 -1
  61. package/dist/config/written-stack.d.ts.map +1 -1
  62. package/dist/config/written-stack.js +6 -2
  63. package/dist/config/written-stack.js.map +1 -1
  64. package/dist/generate/kinds/generate-repository.js +5 -4
  65. package/dist/generate/kinds/generate-repository.js.map +1 -1
  66. package/dist/help/usage.d.ts +1 -1
  67. package/dist/help/usage.d.ts.map +1 -1
  68. package/dist/help/usage.js +1 -1
  69. package/dist/init/manifest/versions.js +23 -23
  70. package/dist/init/stack/resolve-stack.d.ts.map +1 -1
  71. package/dist/init/stack/resolve-stack.js +2 -0
  72. package/dist/init/stack/resolve-stack.js.map +1 -1
  73. package/dist/init/stack/resolve-tenancy.d.ts +8 -0
  74. package/dist/init/stack/resolve-tenancy.d.ts.map +1 -0
  75. package/dist/init/stack/resolve-tenancy.js +31 -0
  76. package/dist/init/stack/resolve-tenancy.js.map +1 -0
  77. package/dist/init/stack/stack-options.d.ts +1 -0
  78. package/dist/init/stack/stack-options.d.ts.map +1 -1
  79. package/dist/stack/stack-vars.d.ts.map +1 -1
  80. package/dist/stack/stack-vars.js +2 -1
  81. package/dist/stack/stack-vars.js.map +1 -1
  82. package/dist/version.d.ts +1 -1
  83. package/dist/version.js +1 -1
  84. package/package.json +2 -2
  85. package/templates/init/platform/audit/audit.module.manual.ts.tpl +5 -0
  86. package/templates/init/platform/audit/audit.module.tsyringe.ts.tpl +5 -0
  87. package/templates/init/platform/audit/create-audit.ts.tpl +24 -0
  88. package/templates/init/platform/audit/search-audit-entries.handler.ts.tpl +13 -0
  89. package/templates/init/platform/audit/search-audit-entries.query.ts.tpl +5 -0
  90. package/templates/init/platform/auth/http-boundary.ts.tpl +38 -1
  91. package/templates/init/platform/compose-application.manual.ts.tpl +3 -0
  92. package/templates/init/platform/compose-application.tsyringe.ts.tpl +14 -0
  93. package/templates/init/platform/database/persistence-over.knex.ts.tpl +5 -0
  94. package/templates/init/platform/database/schema.drizzle.ts.tpl +8 -0
  95. package/templates/init/platform/database/schema.knex.ts.tpl +6 -0
  96. package/templates/init/rules/infrastructure.md.tpl +3 -0
  97. package/templates/pipeline/package-scripts.json +1 -1
  98. package/templates/repository/drizzle/repository.ts.tpl +7 -8
  99. package/templates/repository/knex/repository.ts.tpl +32 -12
@@ -22,7 +22,12 @@ export function auditModule(audit: Audit): ContextModule {
22
22
  name: 'audit',
23
23
  register(builder) {
24
24
  builder.bind(AuditTrail).toValue(audit.trail);
25
+ {{#if tenancy.any}}
26
+ builder.bind(AuditReader).toValue(audit.reader);
27
+ {{/if}}
28
+ {{#unless tenancy.any}}
25
29
  builder.bind(AuditReader).toValue(audit.trail);
30
+ {{/unless}}
26
31
  {{#if audit.route}}
27
32
  {{#if authz.rebac}}
28
33
 
@@ -1,22 +1,32 @@
1
1
  {{#if audit.sql}}
2
2
  import {
3
+ {{#if tenancy.any}}
4
+ TenantAuditReader,
5
+ {{/if}}
3
6
  auditDecisions,
7
+ auditGuardRefusals,
4
8
  auditIntegrationEvents,
5
9
  auditMiddleware,
6
10
  type AuditReader,
7
11
  type AuditSource,
8
12
  type AuditTrail,
13
+ type GuardRefusalOfARoute,
9
14
  } from '@ddd-ts-kit/audit';
10
15
  {{/if}}
11
16
  {{#if audit.memory}}
12
17
  import {
13
18
  InMemoryAuditTrail,
19
+ {{#if tenancy.any}}
20
+ TenantAuditReader,
21
+ {{/if}}
14
22
  auditDecisions,
23
+ auditGuardRefusals,
15
24
  auditIntegrationEvents,
16
25
  auditMiddleware,
17
26
  type AuditReader,
18
27
  type AuditSource,
19
28
  type AuditTrail,
29
+ type GuardRefusalOfARoute,
20
30
  } from '@ddd-ts-kit/audit';
21
31
  {{/if}}
22
32
  {{#if audit.knex}}
@@ -50,8 +60,18 @@ const consumer = 'audit';
50
60
  */
51
61
  export interface Audit {
52
62
  readonly trail: AuditTrail & AuditReader;
63
+ {{#if tenancy.any}}
64
+ /**
65
+ * The trail as the read side searches it: confined to the tenant of the work in progress,
66
+ * whatever the filter or the actor says. Platform staff read across tenants only inside
67
+ * `acrossTenants`, which records the elevation first; work in no tenant is refused.
68
+ */
69
+ readonly reader: AuditReader;
70
+ {{/if}}
53
71
  /** The `onDecision` hook of the authorization: who was allowed or refused what. */
54
72
  readonly decisions: OnDecision;
73
+ /** The `onGuardRefusal` hook of the HTTP pipeline: who a guard refused at the edge, before any use case. */
74
+ readonly refusals: (refusal: GuardRefusalOfARoute) => Promise<void>;
55
75
  /** On the command bus, before the unit of work: which command ran and how it ended. */
56
76
  readonly commands: BusMiddleware;
57
77
  /** On the query bus: whoever reads the trail leaves an entry in it. */
@@ -68,6 +88,10 @@ export function createAudit(persistence: Persistence, source: AuditSource): Audi
68
88
 
69
89
  return {
70
90
  trail,
91
+ {{#if tenancy.any}}
92
+ reader: new TenantAuditReader(trail, source.scope),
93
+ {{/if}}
94
+ refusals: auditGuardRefusals(trail, source),
71
95
  {{#if audit.route}}
72
96
  decisions: auditDecisions(trail, { ...source, sensitivePermissions: [auditPermissions['trail.read'].id] }),
73
97
  // TODO(platform): declare what may go into `changes` with `fields: [auditedFields(SomeCommand, ['status'])]`; by default an entry carries identifiers and codes only.
@@ -5,6 +5,18 @@ import type { SearchAuditEntriesQuery } from '{{alias.platform}}/audit/search-au
5
5
  export class SearchAuditEntriesHandler implements QueryHandler<SearchAuditEntriesQuery> {
6
6
  constructor(private readonly reader: AuditReader) {}
7
7
 
8
+ {{#if tenancy.any}}
9
+ /**
10
+ * The permission was decided by the guard of the bus. The reader is the tenant audit reader
11
+ * of the platform: it bounds the read to the tenant of the work in progress, in the statement
12
+ * and never in memory, whatever the filter says. Platform staff read across tenants only
13
+ * through `acrossTenants`, never because their actor names no tenant.
14
+ */
15
+ async execute(query: SearchAuditEntriesQuery): Promise<Page<AuditEntry>> {
16
+ return this.reader.search(query.filter, query.page);
17
+ }
18
+ {{/if}}
19
+ {{#unless tenancy.any}}
8
20
  /**
9
21
  * The permission was decided by the guard of the bus. The tenant of the actor then bounds the
10
22
  * read itself, in the statement and never in memory: a tenant lists its own chain, and only an
@@ -15,4 +27,5 @@ export class SearchAuditEntriesHandler implements QueryHandler<SearchAuditEntrie
15
27
 
16
28
  return this.reader.search({ ...query.filter, ...(tenantId === undefined ? {} : { tenantId }) }, query.page);
17
29
  }
30
+ {{/unless}}
18
31
  }
@@ -1,7 +1,12 @@
1
1
  import type { AuditEntry, AuditFilter, AuditSortField } from '@ddd-ts-kit/audit';
2
2
  import { AuthorizedQuery, type Actor, type Page, type PageRequest } from '@ddd-ts-kit/kernel';
3
3
 
4
+ {{#if tenancy.any}}
5
+ /** What a reader of the trail may narrow the search by. The tenant is the one of the work, never a filter. */
6
+ {{/if}}
7
+ {{#unless tenancy.any}}
4
8
  /** What a reader of the trail may narrow the search by. The tenant is not among them: it is the one of the actor. */
9
+ {{/unless}}
5
10
  export type AuditEntriesFilter = Pick<AuditFilter, 'actorId' | 'action' | 'outcome' | 'correlationId'>;
6
11
 
7
12
  /** A page of the audit trail, for whoever holds `audit:trail.read`. */
@@ -1,10 +1,21 @@
1
1
  import type { Authenticator } from '@ddd-ts-kit/auth';
2
2
  {{#if errors.none}}
3
- import type { ErrorContext, ErrorMapper, RouteAround } from '@ddd-ts-kit/http';
3
+ import type { ErrorContext, ErrorMapper, {{#if audit.on}}GuardRefusal, {{/if}}RouteAround } from '@ddd-ts-kit/http';
4
4
  import type { Clock, ExecutionScope, Logger, Session } from '@ddd-ts-kit/kernel';
5
5
  {{/if}}
6
6
  {{#if errors.sentry}}
7
+ {{#unless audit.on}}
7
8
  import { reportHttpErrors, type ErrorContext, type ErrorMapper, type RouteAround } from '@ddd-ts-kit/http';
9
+ {{/unless}}
10
+ {{#if audit.on}}
11
+ import {
12
+ reportHttpErrors,
13
+ type ErrorContext,
14
+ type ErrorMapper,
15
+ type GuardRefusal,
16
+ type RouteAround,
17
+ } from '@ddd-ts-kit/http';
18
+ {{/if}}
8
19
  import type { Clock, ErrorReporter, ExecutionScope, Logger, Session } from '@ddd-ts-kit/kernel';
9
20
  {{/if}}
10
21
  import { tracedRoutes } from '@ddd-ts-kit/tracing';
@@ -21,6 +32,10 @@ export interface HttpBoundary {
21
32
  readonly onError: (error: unknown, context: ErrorContext) => void;
22
33
  /** The span of a request, named by its route template; probes and documentation routes make none. */
23
34
  readonly around: RouteAround;
35
+ {{#if audit.on}}
36
+ /** A request a guard refused at the edge, written to the audit trail as a denied decision. */
37
+ readonly onGuardRefusal: (refusal: GuardRefusal) => Promise<void>;
38
+ {{/if}}
24
39
  }
25
40
 
26
41
  interface Edge {
@@ -29,6 +44,10 @@ interface Edge {
29
44
  readonly errorMapper: ErrorMapper;
30
45
  readonly clock: Clock;
31
46
  readonly logger: Logger;
47
+ {{#if audit.on}}
48
+ /** Where a refusal at the edge is recorded: the audit trail. */
49
+ readonly refusals: (refusal: GuardRefusal) => Promise<void>;
50
+ {{/if}}
32
51
  {{#if errors.sentry}}
33
52
  /** Where a request answered 5xx is reported, unless a bus already reported its failure. */
34
53
  readonly errors: ErrorReporter;
@@ -37,7 +56,19 @@ interface Edge {
37
56
 
38
57
  /** A request is authenticated once, then handled inside the execution scope, so infrastructure sees who acts and under which correlation. */
39
58
  {{#if errors.none}}
59
+ {{#unless audit.on}}
40
60
  export function httpBoundary({ authenticator, executionScope, errorMapper, clock, logger }: Edge): HttpBoundary {
61
+ {{/unless}}
62
+ {{#if audit.on}}
63
+ export function httpBoundary({
64
+ authenticator,
65
+ executionScope,
66
+ errorMapper,
67
+ clock,
68
+ logger,
69
+ refusals,
70
+ }: Edge): HttpBoundary {
71
+ {{/if}}
41
72
  {{/if}}
42
73
  {{#if errors.sentry}}
43
74
  export function httpBoundary({
@@ -46,6 +77,9 @@ export function httpBoundary({
46
77
  errorMapper,
47
78
  clock,
48
79
  logger,
80
+ {{#if audit.on}}
81
+ refusals,
82
+ {{/if}}
49
83
  errors,
50
84
  }: Edge): HttpBoundary {
51
85
  const report = reportHttpErrors(errors);
@@ -57,6 +91,9 @@ export function httpBoundary({
57
91
  errorMapper,
58
92
  clock,
59
93
  around: tracedRoutes(),
94
+ {{#if audit.on}}
95
+ onGuardRefusal: refusals,
96
+ {{/if}}
60
97
  // The message of the error may quote data: only the code and the route are logged.
61
98
  {{#if errors.none}}
62
99
  onError: (_error, context) => {
@@ -120,6 +120,9 @@ export function composeApplication(
120
120
  errorMapper: createErrorMapper(),
121
121
  clock,
122
122
  logger,
123
+ {{#if audit.on}}
124
+ refusals: platform.audit.refusals,
125
+ {{/if}}
123
126
  {{#if errors.sentry}}
124
127
  errors: platform.errors,
125
128
  {{/if}}
@@ -38,6 +38,11 @@ import {
38
38
  {{#if http.any}}
39
39
  ExecutionScope,
40
40
  {{/if}}
41
+ {{#if audit.on}}
42
+ {{#if http.any}}
43
+ IdGenerator,
44
+ {{/if}}
45
+ {{/if}}
41
46
  {{#unless broker.external}}
42
47
  IntegrationEventSubscriber,
43
48
  {{/unless}}
@@ -57,6 +62,9 @@ import {
57
62
  } from '@ddd-ts-kit/kernel';
58
63
  import { tracedPublisher } from '@ddd-ts-kit/tracing';
59
64
  {{#if audit.on}}
65
+ {{#if http.any}}
66
+ import { AuditTrail, auditGuardRefusals } from '@ddd-ts-kit/audit';
67
+ {{/if}}
60
68
  import { auditModule } from '{{alias.platform}}/audit/audit.module{{alias.ext}}';
61
69
  {{/if}}
62
70
  {{#if audit.functionRoute}}
@@ -232,6 +240,12 @@ function running(container: Container, options: ApplicationOptions, contexts: Co
232
240
  errorMapper: container.resolve(ErrorMapper),
233
241
  clock: container.resolve(Clock),
234
242
  logger,
243
+ {{#if audit.on}}
244
+ refusals: auditGuardRefusals(container.resolve(AuditTrail), {
245
+ clock: container.resolve(Clock),
246
+ ids: container.resolve(IdGenerator),
247
+ }),
248
+ {{/if}}
235
249
  {{#if errors.sentry}}
236
250
  errors: container.resolve(ErrorReporter),
237
251
  {{/if}}
@@ -10,7 +10,12 @@ export function persistenceOver(db: Knex, close: () => Promise<void>): Persisten
10
10
  return {
11
11
  unitOfWork,
12
12
  database: unitOfWork,
13
+ {{#if tenancy.any}}
14
+ outbox: new KnexOutboxStore(unitOfWork, { schema: MESSAGING, tenant: true }),
15
+ {{/if}}
16
+ {{#unless tenancy.any}}
13
17
  outbox: new KnexOutboxStore(unitOfWork, { schema: MESSAGING }),
18
+ {{/unless}}
14
19
  processedEvents: new KnexProcessedEventStore(unitOfWork, { schema: MESSAGING }),
15
20
  close,
16
21
  };
@@ -1,9 +1,17 @@
1
1
  {{#if audit.on}}
2
2
  import { auditChainsTable, auditEntriesTable } from '@ddd-ts-kit/audit/drizzle';
3
3
  {{/if}}
4
+ {{#if tenancy.any}}
5
+ import { processedEventsTable, tenantOutboxTable } from '@ddd-ts-kit/drizzle/postgres';
6
+
7
+ /** It keeps the tenant of each event, so that its consumers run in that tenant. */
8
+ export const outbox = tenantOutboxTable('messaging');
9
+ {{/if}}
10
+ {{#unless tenancy.any}}
4
11
  import { outboxTable, processedEventsTable } from '@ddd-ts-kit/drizzle/postgres';
5
12
 
6
13
  export const outbox = outboxTable('messaging');
14
+ {{/unless}}
7
15
  export const processedEvents = processedEventsTable('messaging');
8
16
  {{#if audit.on}}
9
17
 
@@ -18,7 +18,13 @@ export const AUDIT_SCHEMA = 'audit';
18
18
  * existing table goes into a migration of its own (`npm run db:generate <what-it-does>`).
19
19
  */
20
20
  export const createTables = async (knex: Knex): Promise<void> => {
21
+ {{#if tenancy.any}}
22
+ // The tenant of each event, so that its consumers run in that tenant.
23
+ await createOutboxTables(knex, { schema: MESSAGING, tenant: true });
24
+ {{/if}}
25
+ {{#unless tenancy.any}}
21
26
  await createOutboxTables(knex, { schema: MESSAGING });
27
+ {{/unless}}
22
28
  {{#if audit.on}}
23
29
  await createAuditTables(knex, { schema: AUDIT_SCHEMA });
24
30
  {{/if}}
@@ -10,6 +10,9 @@ paths:
10
10
  - Rows never leave `persistence/`: a mapper translates to and from the aggregate, and is the only place for a type assertion (`clean/no-escape-hatch`).
11
11
  - Own tables, in the schema of the context: no join, foreign key or transaction across contexts (`context/extractable`).
12
12
  - Audit columns and the tenant column are stamped from the execution scope with the kernel helpers (`stampCreation`, `stampUpdate`, `tenantScopeOf`), never handed over by a use case.
13
+ {{#if tenancy.any}}
14
+ - Tenant data is reached through the helpers of the ORM package, never straight from the executor: {{#if orm.knex}}`tenantTable` to read, `ownTenantTable` to update or delete{{/if}}{{#if orm.drizzle}}`tenantCondition` in the condition of a read, `ownTenantCondition` in that of an update or a delete{{/if}}, the tenant named on every insert (`tenancy/scoped-statement`). A table of no tenant is a recorded deviation. See `docs/concepts/multitenancy.md` of the kit.
15
+ {{/if}}
13
16
  {{#if style.declared}}
14
17
  - An adapter declares itself on its class, one per file (`declarations/role-declared`): `@Repository(InvoiceRepository)`, `@Gateway(Port)` or `@Adapter(Port, { kind })`. What it is given is what its constructor takes, each parameter typed by one class (`{{persistence.tokenOrNone}}`, `ExecutionScope`, `Clock`, a port, an abstract class the platform binds to a value) and nothing listed in the decorator (`declarations/constructor-injection`); an adapter that extends a class of a package writes its own constructor.
15
18
  - Retry, timeout and cache go on the declaration (`aspects: [ownPolicy(retry(...), timeout(...))]`) or, when the policy is part of what the adapter is, as decorators of `@ddd-ts-kit/aspects/decorators` (`aspects/outside-in`). Kinds `external` and `gateway` get the default policy of the platform otherwise. `ownPolicy` is the helper of `{{alias.platform}}/resilience/own-policy{{alias.ext}}`, which `generate adapter` writes when the platform does not have it yet.
@@ -23,7 +23,7 @@
23
23
  "@biomejs/biome": "2.5.15",
24
24
  "@commitlint/cli": "^21.2.3",
25
25
  "@commitlint/config-conventional": "^21.2.3",
26
- "@ddd-ts-kit/eslint-plugin": "^0.7.0",
26
+ "@ddd-ts-kit/eslint-plugin": "^0.8.0",
27
27
  "@eslint/js": "^10.0.1",
28
28
  "@typescript/native": "npm:typescript@~7.0.2",
29
29
  "@vitest/coverage-v8": "5.0.3",
@@ -1,5 +1,10 @@
1
1
  import { and, eq } from 'drizzle-orm';
2
+ {{#if tenant.scoped}}
3
+ import { optimisticUpdate, ownTenantCondition, tenantCondition } from '@ddd-ts-kit/drizzle/postgres';
4
+ {{/if}}
5
+ {{#unless tenant.scoped}}
2
6
  import { optimisticUpdate } from '@ddd-ts-kit/drizzle/postgres';
7
+ {{/unless}}
3
8
  {{#if tenant.scoped}}
4
9
  import { stampCreation, stampUpdate, tenantScopeOf, type Clock, type ExecutionScope } from '@ddd-ts-kit/kernel';
5
10
  {{/if}}
@@ -34,7 +39,7 @@ export class Drizzle{{aggregate.pascal}}Repository implements {{aggregate.pascal
34
39
 
35
40
  async findById(id: string): Promise<{{aggregate.pascal}} | undefined> {
36
41
  {{#if tenant.scoped}}
37
- const mine = and(eq({{aggregate.tableCamel}}.id, id), this.ownTenant());
42
+ const mine = and(eq({{aggregate.tableCamel}}.id, id), tenantCondition({{aggregate.tableCamel}}.tenantId, this.scope));
38
43
  const [row] = await this.database.executor().select().from({{aggregate.tableCamel}}).where(mine);
39
44
  {{/if}}
40
45
  {{#unless tenant.scoped}}
@@ -70,13 +75,7 @@ export class Drizzle{{aggregate.pascal}}Repository implements {{aggregate.pascal
70
75
  .executor()
71
76
  .update({{aggregate.tableCamel}})
72
77
  .set({ ...state, ...stampUpdate(this.scope, this.clock) })
73
- .where(and(sameId, sameVersion{{#if tenant.scoped}}, this.ownTenant(){{/if}}))
78
+ .where(and(sameId, sameVersion{{#if tenant.scoped}}, ownTenantCondition({{aggregate.tableCamel}}.tenantId, this.scope){{/if}}))
74
79
  .returning({ id: {{aggregate.tableCamel}}.id });
75
80
  }
76
- {{#if tenant.scoped}}
77
-
78
- private ownTenant() {
79
- return eq({{aggregate.tableCamel}}.tenantId, tenantScopeOf(this.scope).tenantId);
80
- }
81
- {{/if}}
82
81
  }
@@ -1,4 +1,6 @@
1
+ {{#unless tenant.scoped}}
1
2
  import type { Knex } from 'knex';
3
+ {{/unless}}
2
4
  {{#if tenant.scoped}}
3
5
  import { stampCreation, stampUpdate, tenantScopeOf, type Clock, type ExecutionScope } from '@ddd-ts-kit/kernel';
4
6
  {{/if}}
@@ -14,8 +16,9 @@ import {
14
16
  auditRow,
15
17
  insertIgnoringConflict,
16
18
  optimisticUpdate,
19
+ ownTenantTable,
17
20
  tenantRow,
18
- type TenantRow,
21
+ tenantTable,
19
22
  } from '@ddd-ts-kit/knex';
20
23
  {{/if}}
21
24
  {{#unless tenant.scoped}}
@@ -33,6 +36,11 @@ import { {{aggregate.pascal}}Mapper } from '{{alias.context}}/infrastructure/per
33
36
  import type { {{aggregate.pascal}}Columns, {{aggregate.pascal}}Row } from '{{alias.context}}/infrastructure/persistence/{{aggregate.kebab}}-row.schema{{alias.ext}}';
34
37
 
35
38
  type Versioned{{aggregate.pascal}} = {{aggregate.pascal}}Columns & { readonly version: number };
39
+ {{#if tenant.scoped}}
40
+
41
+ /** Tenant data: every statement reaches it through `tenantTable` or `ownTenantTable`, confined to the tenant of the work. */
42
+ const TABLE = { schema: {{context.constant}}_SCHEMA, table: '{{aggregate.table}}' };
43
+ {{/if}}
36
44
 
37
45
  {{#if style.declared}}
38
46
  @Repository({{aggregate.pascal}}Repository)
@@ -46,9 +54,7 @@ export class Knex{{aggregate.pascal}}Repository implements {{aggregate.pascal}}R
46
54
 
47
55
  async findById(id: string): Promise<{{aggregate.pascal}} | undefined> {
48
56
  {{#if tenant.scoped}}
49
- const row = await tableOf(this.database)
50
- .where({ id, ...this.ownTenant() })
51
- .first();
57
+ const row = await tenantTable<{{aggregate.pascal}}Row>(this.database, this.scope, TABLE).where({ id }).first();
52
58
  {{/if}}
53
59
  {{#unless tenant.scoped}}
54
60
  const row = await tableOf(this.database).where({ id }).first();
@@ -65,8 +71,27 @@ export class Knex{{aggregate.pascal}}Repository implements {{aggregate.pascal}}R
65
71
  });
66
72
  }
67
73
 
74
+ {{#if tenant.scoped}}
68
75
  private async insert(state: Versioned{{aggregate.pascal}}): Promise<number> {
69
- const row = { ...state, {{#if tenant.scoped}}...this.ownTenant(), {{/if}}...auditRow(stampCreation(this.scope, this.clock)) };
76
+ const tenant = tenantRow(tenantScopeOf(this.scope));
77
+ const row = { ...state, ...tenant, ...auditRow(stampCreation(this.scope, this.clock)) };
78
+ const table = ownTenantTable<{{aggregate.pascal}}Row>(this.database, this.scope, TABLE);
79
+
80
+ const inserted = await insertIgnoringConflict(this.database.executor(), table, { row, conflict: 'id' });
81
+
82
+ return inserted ? 1 : 0;
83
+ }
84
+
85
+ private async update(state: Versioned{{aggregate.pascal}}, expected: number): Promise<number> {
86
+ return ownTenantTable<{{aggregate.pascal}}Row>(this.database, this.scope, TABLE)
87
+ .where({ id: state.id, version: expected })
88
+ .update({ ...state, ...auditRow(stampUpdate(this.scope, this.clock)) });
89
+ }
90
+ }
91
+ {{/if}}
92
+ {{#unless tenant.scoped}}
93
+ private async insert(state: Versioned{{aggregate.pascal}}): Promise<number> {
94
+ const row = { ...state, ...auditRow(stampCreation(this.scope, this.clock)) };
70
95
 
71
96
  const inserted = await insertIgnoringConflict(this.database.executor(), tableOf(this.database), {
72
97
  row,
@@ -78,15 +103,9 @@ export class Knex{{aggregate.pascal}}Repository implements {{aggregate.pascal}}R
78
103
 
79
104
  private async update(state: Versioned{{aggregate.pascal}}, expected: number): Promise<number> {
80
105
  return tableOf(this.database)
81
- .where({ id: state.id, version: expected{{#if tenant.scoped}}, ...this.ownTenant(){{/if}} })
106
+ .where({ id: state.id, version: expected })
82
107
  .update({ ...state, ...auditRow(stampUpdate(this.scope, this.clock)) });
83
108
  }
84
- {{#if tenant.scoped}}
85
-
86
- private ownTenant(): TenantRow {
87
- return tenantRow(tenantScopeOf(this.scope));
88
- }
89
- {{/if}}
90
109
  }
91
110
 
92
111
  /** A function and not a method: a query builder is thenable, and a method that answers one is read as asynchronous by whatever wraps the adapter (tracing), which then answers a promise. */
@@ -95,3 +114,4 @@ function tableOf(database: KnexContext): Knex.QueryBuilder<{{aggregate.pascal}}R
95
114
 
96
115
  return table.withSchema({{context.constant}}_SCHEMA);
97
116
  }
117
+ {{/unless}}