@cqrs-ddd/mikro-orm 0.2.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 (64) hide show
  1. package/COMMERCIAL_LICENSE.txt +34 -0
  2. package/LICENSE +661 -0
  3. package/README.md +299 -0
  4. package/dist/cache/cache-entry.d.ts +43 -0
  5. package/dist/cache/cache-entry.d.ts.map +1 -0
  6. package/dist/cache/cache-entry.js +92 -0
  7. package/dist/cache/cache-entry.js.map +1 -0
  8. package/dist/cache/mikro-orm.cache.d.ts +82 -0
  9. package/dist/cache/mikro-orm.cache.d.ts.map +1 -0
  10. package/dist/cache/mikro-orm.cache.js +209 -0
  11. package/dist/cache/mikro-orm.cache.js.map +1 -0
  12. package/dist/concurrency/assert-autocommit.d.ts +21 -0
  13. package/dist/concurrency/assert-autocommit.d.ts.map +1 -0
  14. package/dist/concurrency/assert-autocommit.js +27 -0
  15. package/dist/concurrency/assert-autocommit.js.map +1 -0
  16. package/dist/concurrency/conditioned-write.d.ts +23 -0
  17. package/dist/concurrency/conditioned-write.d.ts.map +1 -0
  18. package/dist/concurrency/conditioned-write.js +26 -0
  19. package/dist/concurrency/conditioned-write.js.map +1 -0
  20. package/dist/concurrency/optimistic-delete.d.ts +52 -0
  21. package/dist/concurrency/optimistic-delete.d.ts.map +1 -0
  22. package/dist/concurrency/optimistic-delete.js +67 -0
  23. package/dist/concurrency/optimistic-delete.js.map +1 -0
  24. package/dist/concurrency/optimistic-update.d.ts +51 -0
  25. package/dist/concurrency/optimistic-update.d.ts.map +1 -0
  26. package/dist/concurrency/optimistic-update.js +60 -0
  27. package/dist/concurrency/optimistic-update.js.map +1 -0
  28. package/dist/errors/mikro-orm.dialect.d.ts +32 -0
  29. package/dist/errors/mikro-orm.dialect.d.ts.map +1 -0
  30. package/dist/errors/mikro-orm.dialect.js +96 -0
  31. package/dist/errors/mikro-orm.dialect.js.map +1 -0
  32. package/dist/errors/transient-error.d.ts +51 -0
  33. package/dist/errors/transient-error.d.ts.map +1 -0
  34. package/dist/errors/transient-error.js +97 -0
  35. package/dist/errors/transient-error.js.map +1 -0
  36. package/dist/helpers/sql-identifier.d.ts +19 -0
  37. package/dist/helpers/sql-identifier.d.ts.map +1 -0
  38. package/dist/helpers/sql-identifier.js +23 -0
  39. package/dist/helpers/sql-identifier.js.map +1 -0
  40. package/dist/index.d.ts +14 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +31 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/interfaces/entity-manager-source.d.ts +19 -0
  45. package/dist/interfaces/entity-manager-source.d.ts.map +1 -0
  46. package/dist/interfaces/entity-manager-source.js +4 -0
  47. package/dist/interfaces/entity-manager-source.js.map +1 -0
  48. package/dist/mapping/root-entity.properties.d.ts +63 -0
  49. package/dist/mapping/root-entity.properties.d.ts.map +1 -0
  50. package/dist/mapping/root-entity.properties.js +63 -0
  51. package/dist/mapping/root-entity.properties.js.map +1 -0
  52. package/dist/mapping/unix-timestamp.type.d.ts +17 -0
  53. package/dist/mapping/unix-timestamp.type.d.ts.map +1 -0
  54. package/dist/mapping/unix-timestamp.type.js +55 -0
  55. package/dist/mapping/unix-timestamp.type.js.map +1 -0
  56. package/dist/repository/aggregate.repository.d.ts +68 -0
  57. package/dist/repository/aggregate.repository.d.ts.map +1 -0
  58. package/dist/repository/aggregate.repository.js +103 -0
  59. package/dist/repository/aggregate.repository.js.map +1 -0
  60. package/dist/tenancy/tenant-store.d.ts +63 -0
  61. package/dist/tenancy/tenant-store.d.ts.map +1 -0
  62. package/dist/tenancy/tenant-store.js +91 -0
  63. package/dist/tenancy/tenant-store.js.map +1 -0
  64. package/package.json +57 -0
package/README.md ADDED
@@ -0,0 +1,299 @@
1
+ # @cqrs-ddd/mikro-orm
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@cqrs-ddd/mikro-orm.svg)](https://www.npmjs.com/package/@cqrs-ddd/mikro-orm)
4
+ [![License](https://img.shields.io/npm/l/@cqrs-ddd/mikro-orm.svg)](https://www.npmjs.com/package/@cqrs-ddd/mikro-orm)
5
+
6
+ MikroORM 7 adapters for [`@cqrs-ddd/core`](https://www.npmjs.com/package/@cqrs-ddd/core):
7
+ authoritative aggregate loading, version-conditioned writes, the persistence dialect
8
+ that maps unique violations and transient failures, a revision-fenced cache stored in
9
+ the database, and the `EntitySchema` mapping of `RootEntity`.
10
+
11
+ `@cqrs-ddd/core` depends on no ORM; this package is where MikroORM enters. It depends
12
+ on no framework: it works in a plain Node service and in a NestJS application.
13
+
14
+ ## Contents
15
+
16
+ - [Installation](#installation)
17
+ - [Entity manager source](#entity-manager-source)
18
+ - [Multi-tenant store](#multi-tenant-store)
19
+ - [Loading aggregates](#loading-aggregates)
20
+ - [Version-conditioned writes](#version-conditioned-writes)
21
+ - [Persistence errors](#persistence-errors)
22
+ - [Mapping a root entity](#mapping-a-root-entity)
23
+ - [The database cache](#the-database-cache)
24
+ - [SQL identifiers](#sql-identifiers)
25
+ - [License](#license)
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pnpm add @cqrs-ddd/mikro-orm @cqrs-ddd/core @mikro-orm/core
31
+ ```
32
+
33
+ Requires Node.js 22 or later. `@cqrs-ddd/core` and `@mikro-orm/core` 7 are peer
34
+ dependencies; add the MikroORM driver you use, such as `@mikro-orm/postgresql`.
35
+
36
+ ## Entity manager source
37
+
38
+ The adapters take an `IEntityManagerSource`, an object with an `em` property, and read
39
+ `em` on every operation. A multi-tenant store can therefore hand out the current
40
+ tenant's manager; a single-database setup can pass `{ em: orm.em.fork() }`.
41
+
42
+ ## Multi-tenant store
43
+
44
+ `TenantStore` is that source for a multi-tenant application. `em` and `transactional()`
45
+ act on the active tenant, which `tenant()` supplies; `orm(tenant)` returns the initialized
46
+ ORM holding its data. Both throw when there is no tenant or it is unknown: the store never
47
+ falls back to one.
48
+
49
+ ```typescript
50
+ import { AsyncLocalStorage } from 'node:async_hooks';
51
+ import { setPersistenceDialect } from '@cqrs-ddd/core/persistence';
52
+ import { CacheEntrySchema, MikroOrmDialect, TenantStore } from '@cqrs-ddd/mikro-orm';
53
+ import { MikroORM } from '@mikro-orm/core';
54
+
55
+ const requestTenant = new AsyncLocalStorage<string>();
56
+ const orms = new Map<string, MikroORM>();
57
+ for (const tenant of ['tenant_a', 'tenant_b']) {
58
+ orms.set(tenant, await MikroORM.init({ ...tenantOptions(tenant), entities: [UserSchema, CacheEntrySchema] }));
59
+ }
60
+
61
+ const store = new TenantStore({
62
+ tenant: () => {
63
+ const tenant = requestTenant.getStore();
64
+ if (!tenant) throw new Error('No tenant in scope.');
65
+ return tenant;
66
+ },
67
+ orm: (tenant) => {
68
+ const orm = orms.get(tenant);
69
+ if (!orm) throw new Error(`Unknown tenant ${tenant}.`);
70
+ return orm;
71
+ },
72
+ isolation: 'database', // one ORM and database per tenant; 'schema': one ORM, a schema per tenant
73
+ });
74
+
75
+ const [first] = orms.values();
76
+ if (first) setPersistenceDialect(new MikroOrmDialect(first));
77
+
78
+ await requestTenant.run('tenant_a', () => store.em.findOne(User, { id }));
79
+ await requestTenant.run('tenant_a', () =>
80
+ store.transactional((em) => em.nativeDelete(CacheEntry, { key })),
81
+ );
82
+ ```
83
+
84
+ With `'schema'` isolation, `orm` returns the same ORM for every tenant and each manager is
85
+ forked with `schema: tenant`; validate the tenant against a known list before it reaches
86
+ the store, for example with `isSqlIdentifier`.
87
+
88
+ - `em` reuses the contextual manager (a MikroORM `RequestContext` or an active
89
+ transaction) only when it belongs to the tenant's ORM, configuration, driver and schema,
90
+ and no other tenant used it first. Otherwise it forks one, with the tenant's schema under
91
+ `'schema'` isolation.
92
+ - `transactional()` always runs on a fork of its own; a missing or unknown tenant rejects
93
+ it.
94
+ - The tenant of each manager it hands out is kept in a `WeakMap`: MikroORM objects are
95
+ never modified.
96
+
97
+ ## Loading aggregates
98
+
99
+ A command that mutates an aggregate loads it through core's
100
+ `IWriteSideAggregateRepository<TEntity>.findById(id)`. `AggregateRepository` implements
101
+ it: `findById()` reads with `{ refresh: true }`, never touches the cache, rehydrates
102
+ through the `hydrateFn` you pass, and translates driver failures with
103
+ `mapPersistenceError`.
104
+
105
+ ```typescript
106
+ import type { ICache } from '@cqrs-ddd/core/application';
107
+ import { cacheKey, PersistedWrite } from '@cqrs-ddd/core/persistence';
108
+ import { AggregateRepository, type IEntityManagerSource, optimisticUpdate } from '@cqrs-ddd/mikro-orm';
109
+
110
+ export class UpdateUserRepository extends AggregateRepository<UserSnapshot, User, UserSnapshot> {
111
+ constructor(cache: ICache<UserSnapshot>, store: IEntityManagerSource) {
112
+ super(cache, store, User, User.aggregateName, User.fromJSON);
113
+ }
114
+
115
+ @PersistedWrite<User>({
116
+ cache: { setKey: (user) => cacheKey(User.aggregateName, { id: user.id }) },
117
+ })
118
+ async save(user: User): Promise<UserSnapshot> {
119
+ const snapshot = user.toJSON();
120
+ await optimisticUpdate(
121
+ this.store.em,
122
+ User,
123
+ user,
124
+ { username: snapshot.username, updatedAt: snapshot.updatedAt },
125
+ 'User',
126
+ );
127
+ return snapshot;
128
+ }
129
+ }
130
+
131
+ const users = new UpdateUserRepository(cache, store);
132
+ const user = await users.findById(id); // always the database row, never the cache
133
+ ```
134
+
135
+ ## Version-conditioned writes
136
+
137
+ `optimisticUpdate` and `optimisticDelete` write `WHERE id = ? AND version = expected`,
138
+ check the affected rows, and raise core's `EntityNotFoundException` or
139
+ `ConcurrencyConflictError`. They, and every write whose success triggers acknowledgment
140
+ or cache work, call `assertAutocommit(em, operation)` first: a write inside an outer
141
+ transaction is rejected before any statement runs, because its success would not mean
142
+ durable persistence.
143
+
144
+ ```typescript
145
+ import { ConcurrencyConflictError } from '@cqrs-ddd/core/domain';
146
+ import { optimisticDelete, optimisticUpdate } from '@cqrs-ddd/mikro-orm';
147
+
148
+ // UPDATE users SET department = ?, updated_at = ?, version = <user.version>
149
+ // WHERE id = <user.id> AND version = <user.getExpectedVersion()>
150
+ await optimisticUpdate(store.em, User, user, { department: 'Research', updatedAt: user.updatedAt }, 'User');
151
+
152
+ try {
153
+ await optimisticDelete(store.em, User, staleUser, 'User');
154
+ } catch (error) {
155
+ if (error instanceof ConcurrencyConflictError) {
156
+ // error.expectedVersion is the version staleUser was loaded at; reload and retry
157
+ }
158
+ throw error;
159
+ }
160
+
161
+ await store.em.transactional((em) => optimisticUpdate(em, User, user, fields, 'User')); // rejected
162
+ ```
163
+
164
+ - `data` holds the columns to write; `version` is set from `entity.version`, so a caller
165
+ lists every other changed column, `updatedAt` included.
166
+ - No matching row: a refreshed read tells a missing row (`EntityNotFoundException`) from a
167
+ diverged version (`ConcurrencyConflictError`). More than one matching row throws an
168
+ `Error`.
169
+ - Neither function touches the cache, acknowledges the aggregate or publishes events;
170
+ `@PersistedWrite`, `@Cache` and `CommandBaseHandler` do that.
171
+
172
+ ## Persistence errors
173
+
174
+ `MikroOrmDialect` implements core's `IPersistenceDialect`. Register it once the ORM is
175
+ initialized, and `@MapPersistenceErrors` / `@PersistedWrite` map unique violations by
176
+ entity property:
177
+
178
+ ```typescript
179
+ import { setPersistenceDialect } from '@cqrs-ddd/core/persistence';
180
+ import { MikroOrmDialect } from '@cqrs-ddd/mikro-orm';
181
+
182
+ const orm = await MikroORM.init(options);
183
+ setPersistenceDialect(new MikroOrmDialect(orm));
184
+
185
+ // in a repository
186
+ @PersistedWrite<User>({ unique: { email: (user) => new UniqueEmailException(user) } })
187
+ async save(user: User): Promise<UserSnapshot> {
188
+ const snapshot = user.toJSON();
189
+ await optimisticUpdate(this.store.em, User, user, { email: snapshot.email }, 'User');
190
+ return snapshot;
191
+ }
192
+ ```
193
+
194
+ A multi-property constraint is keyed by its declared name, passed as the constraint type:
195
+
196
+ ```typescript
197
+ const ROLE_NAME = 'roles_tenant_name_unique';
198
+ // schema: uniques: [{ name: ROLE_NAME, properties: ['tenantId', 'name'] }]
199
+
200
+ @PersistedWrite<Role, typeof ROLE_NAME>({
201
+ unique: { [ROLE_NAME]: (role) => new DuplicateRoleNameException(role) },
202
+ })
203
+ ```
204
+
205
+ It reads each entity's unique constraints from the ORM metadata: `unique: true` or
206
+ `unique: 'name'` on a property, and `uniques: [{ name?, properties }]` on the schema. A
207
+ single-property constraint is keyed by that property; a multi-property one by its
208
+ `name`, which it must declare. For a `UniqueConstraintViolationException`, PostgreSQL's
209
+ reported constraint name is matched against the declared name, or the naming strategy's
210
+ `indexName` when none is declared, and SQLite's reported `table.column` list against the
211
+ constraint's columns. Anything else yields no match and the original error is rethrown.
212
+ Construction fails when two constraints of one entity cover the same columns, because
213
+ SQLite could not tell them apart. Declare constraint names in the mapping, never in a
214
+ repository.
215
+
216
+ `mapPersistenceError(error, operation)` is the `otherwise` translator for transient
217
+ failures: `isTransientPersistenceError` recognizes retryable PostgreSQL SQLSTATEs
218
+ (`40001`, `40P01`, `55P03`, `57P01`–`57P03`, classes `08` and `53`), Node network errors,
219
+ `SQLITE_BUSY`/`SQLITE_LOCKED` and timeouts, through the `cause` chain, and wraps them in
220
+ core's `TransientOperationError`. Any other error is returned unchanged.
221
+
222
+ ## Mapping a root entity
223
+
224
+ `rootEntityProperties(columns?)` and `versionProperty(column?)` give the `EntitySchema`
225
+ properties every `RootEntity` needs, with timestamps stored as epoch milliseconds
226
+ through `UnixTimestampType`. That type throws a `TypeError` for a value with no valid
227
+ time instead of storing `NaN`. The properties use `accessor: true`, so MikroORM reads
228
+ and writes them through the entity's getters and private setters, and queries use the
229
+ public names.
230
+
231
+ ```typescript
232
+ export const UserSchema = new EntitySchema<User, AggregateRoot>({
233
+ class: User as any,
234
+ tableName: 'users',
235
+ properties: {
236
+ ...rootEntityProperties(),
237
+ version: versionProperty(),
238
+ username: { type: 'string', length: 255, accessor: true },
239
+ department: { type: 'string', length: 255, nullable: true, accessor: true },
240
+ email: { type: 'string', length: 320, unique: true },
241
+ },
242
+ });
243
+ ```
244
+
245
+ `rootEntityProperties({ createdAt: 'created', updatedAt: 'modified' })` renames the
246
+ columns; the defaults are `id`, `created_at` and `updated_at`.
247
+
248
+ Map a subclass's fields the same way. An entity written without version checks has no
249
+ version column; map its inherited `version` as `{ type: 'number', persist: false }`.
250
+
251
+ ## The database cache
252
+
253
+ `MikroOrmCache(store, { defaultTtlMs?, logger? })` implements core's `IVersionedCache`
254
+ with one database row per key; every write is a compare-and-set in its own transaction.
255
+ `store` provides `em` and `transactional(work)`. Register `CacheEntrySchema` (or
256
+ `createCacheEntrySchema(table)`) with the ORM, and create the table in a migration with
257
+ `createCacheTableSql(table?)`, which covers PostgreSQL and SQLite.
258
+
259
+ ```typescript
260
+ import { CACHE_TOKEN } from '@cqrs-ddd/core/persistence';
261
+ import { createCacheTableSql, MikroOrmCache } from '@cqrs-ddd/mikro-orm';
262
+
263
+ // once, in a migration
264
+ await orm.em.getConnection().execute(createCacheTableSql());
265
+
266
+ const cache = new MikroOrmCache<UserSnapshot>(store, {
267
+ defaultTtlMs: 5 * 60_000, // 0 never expires
268
+ logger: { warn: (message) => console.warn(message) },
269
+ });
270
+ const users = new UpdateUserRepository(cache, store);
271
+ const reads = new GetUserRepository(cache, store);
272
+
273
+ // NestJS
274
+ {
275
+ provide: CACHE_TOKEN,
276
+ useFactory: (store: TenantStore) => new MikroOrmCache(store, { logger: new Logger('MikroOrmCache') }),
277
+ inject: [STORE],
278
+ }
279
+ ```
280
+
281
+ - `store.transactional(work)` must run `work` on a manager of its own, never the caller's
282
+ request or transaction manager; `TenantStore` does, and so does
283
+ `{ em: orm.em, transactional: (work) => orm.em.fork().transactional(work) }`.
284
+ - With a `TenantStore`, each tenant's cache rows live in that tenant's database or schema.
285
+ - Reads bypass the identity map, a reader never deletes an expired row, and a corrupted
286
+ payload throws instead of reading as a miss.
287
+ - `set` and `invalidate` throw when their compare-and-set cannot settle after 16 attempts.
288
+
289
+ ## SQL identifiers
290
+
291
+ `isSqlIdentifier(name, { qualified? })` accepts an unquoted SQL identifier, optionally
292
+ schema-qualified. Use it before interpolating a name, such as a tenant schema, into SQL
293
+ text, where it cannot be passed as a parameter.
294
+
295
+ ## License
296
+
297
+ Dual-licensed under **AGPL-3.0-or-later** or a **Commercial License**. See
298
+ [`LICENSE`](https://github.com/aristoteliss/nestjs-pipeline/blob/master/LICENSE) and [`COMMERCIAL_LICENSE.txt`](https://github.com/aristoteliss/nestjs-pipeline/blob/master/COMMERCIAL_LICENSE.txt)
299
+ at the repository root.
@@ -0,0 +1,43 @@
1
+ import { EntitySchema } from '@mikro-orm/core';
2
+ /**
3
+ * One row of the {@link MikroOrmCache} table.
4
+ *
5
+ * `value` holds the JSON-serialized snapshot, or `''` after an invalidation;
6
+ * `expiresAt` is epoch milliseconds, or `null` for no expiry; `revision` is the
7
+ * decimal revision token that fences concurrent fills.
8
+ */
9
+ export declare class CacheEntry {
10
+ key: string;
11
+ value: string;
12
+ expiresAt: number | null;
13
+ revision: string;
14
+ }
15
+ /**
16
+ * SQL that creates the {@link MikroOrmCache} table and its expiry index, for
17
+ * PostgreSQL and SQLite. Run it once in a migration. It matches
18
+ * {@link createCacheEntrySchema} for the same `table`.
19
+ *
20
+ * It returns two statements, separated by `;`. The table name is validated as a
21
+ * plain SQL identifier, because it is interpolated, not parameterized.
22
+ *
23
+ * @param table - Table name, optionally schema-qualified. Default `'cache'`.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * await orm.em.getConnection().execute(createCacheTableSql());
28
+ * ```
29
+ */
30
+ export declare function createCacheTableSql(table?: string): string;
31
+ /**
32
+ * MikroORM entity schema for {@link CacheEntry}. Register it with the ORM that
33
+ * backs {@link MikroOrmCache}; pass `table` when the table is not named `cache`.
34
+ *
35
+ * `expires_at` is a `bigint` column, because epoch milliseconds overflow a
36
+ * 32-bit integer.
37
+ *
38
+ * @param table - Table name, optionally schema-qualified. Default `'cache'`.
39
+ */
40
+ export declare function createCacheEntrySchema(table?: string): EntitySchema<CacheEntry>;
41
+ /** {@link createCacheEntrySchema} for the default `cache` table. */
42
+ export declare const CacheEntrySchema: EntitySchema<CacheEntry, never, import("@mikro-orm/core").EntityCtor<CacheEntry>>;
43
+ //# sourceMappingURL=cache-entry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-entry.d.ts","sourceRoot":"","sources":["../../src/cache/cache-entry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAG/C;;;;;;GAMG;AACH,qBAAa,UAAU;IACrB,GAAG,EAAG,MAAM,CAAC;IACb,KAAK,EAAG,MAAM,CAAC;IACf,SAAS,EAAG,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAG,MAAM,CAAC;CACnB;AAYD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,SAAU,GAAG,MAAM,CAU3D;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,SAAU,GACd,YAAY,CAAC,UAAU,CAAC,CAwB1B;AAED,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,mFAA2B,CAAC"}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ /* Copyright (C) 2026-present Aristotelis — see repository license. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.CacheEntrySchema = exports.CacheEntry = void 0;
5
+ exports.createCacheTableSql = createCacheTableSql;
6
+ exports.createCacheEntrySchema = createCacheEntrySchema;
7
+ const core_1 = require("@mikro-orm/core");
8
+ const sql_identifier_1 = require("../helpers/sql-identifier");
9
+ /**
10
+ * One row of the {@link MikroOrmCache} table.
11
+ *
12
+ * `value` holds the JSON-serialized snapshot, or `''` after an invalidation;
13
+ * `expiresAt` is epoch milliseconds, or `null` for no expiry; `revision` is the
14
+ * decimal revision token that fences concurrent fills.
15
+ */
16
+ class CacheEntry {
17
+ key;
18
+ value;
19
+ expiresAt;
20
+ revision;
21
+ }
22
+ exports.CacheEntry = CacheEntry;
23
+ function assertSafeTable(table) {
24
+ if (!(0, sql_identifier_1.isSqlIdentifier)(table, { qualified: true })) {
25
+ throw new Error(`Invalid cache table name "${table}". ` +
26
+ 'Use an unquoted identifier like "cache" or "schema.cache".');
27
+ }
28
+ return table;
29
+ }
30
+ /**
31
+ * SQL that creates the {@link MikroOrmCache} table and its expiry index, for
32
+ * PostgreSQL and SQLite. Run it once in a migration. It matches
33
+ * {@link createCacheEntrySchema} for the same `table`.
34
+ *
35
+ * It returns two statements, separated by `;`. The table name is validated as a
36
+ * plain SQL identifier, because it is interpolated, not parameterized.
37
+ *
38
+ * @param table - Table name, optionally schema-qualified. Default `'cache'`.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * await orm.em.getConnection().execute(createCacheTableSql());
43
+ * ```
44
+ */
45
+ function createCacheTableSql(table = 'cache') {
46
+ const name = assertSafeTable(table);
47
+ const index = `${name.slice(name.lastIndexOf('.') + 1)}_expires_at_idx`;
48
+ return `CREATE TABLE IF NOT EXISTS ${name} (
49
+ key VARCHAR(255) NOT NULL PRIMARY KEY,
50
+ value TEXT NOT NULL,
51
+ expires_at BIGINT,
52
+ revision BIGINT NOT NULL DEFAULT 0
53
+ );
54
+ CREATE INDEX IF NOT EXISTS ${index} ON ${name} (expires_at);`;
55
+ }
56
+ /**
57
+ * MikroORM entity schema for {@link CacheEntry}. Register it with the ORM that
58
+ * backs {@link MikroOrmCache}; pass `table` when the table is not named `cache`.
59
+ *
60
+ * `expires_at` is a `bigint` column, because epoch milliseconds overflow a
61
+ * 32-bit integer.
62
+ *
63
+ * @param table - Table name, optionally schema-qualified. Default `'cache'`.
64
+ */
65
+ function createCacheEntrySchema(table = 'cache') {
66
+ const safe = assertSafeTable(table);
67
+ const index = `${safe.slice(safe.lastIndexOf('.') + 1)}_expires_at_idx`;
68
+ return new core_1.EntitySchema({
69
+ class: CacheEntry,
70
+ tableName: safe,
71
+ properties: {
72
+ key: { type: 'string', length: 255, primary: true },
73
+ value: { type: 'text' },
74
+ expiresAt: {
75
+ type: 'number',
76
+ columnType: 'bigint',
77
+ fieldName: 'expires_at',
78
+ nullable: true,
79
+ },
80
+ revision: { type: 'bigint', fieldName: 'revision', default: 0 },
81
+ },
82
+ indexes: [
83
+ {
84
+ name: index,
85
+ properties: ['expiresAt'],
86
+ },
87
+ ],
88
+ });
89
+ }
90
+ /** {@link createCacheEntrySchema} for the default `cache` table. */
91
+ exports.CacheEntrySchema = createCacheEntrySchema();
92
+ //# sourceMappingURL=cache-entry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-entry.js","sourceRoot":"","sources":["../../src/cache/cache-entry.ts"],"names":[],"mappings":";AAAA,sEAAsE;;;AA4CtE,kDAUC;AAWD,wDA0BC;AAzFD,0CAA+C;AAC/C,8DAA4D;AAE5D;;;;;;GAMG;AACH,MAAa,UAAU;IACrB,GAAG,CAAU;IACb,KAAK,CAAU;IACf,SAAS,CAAiB;IAC1B,QAAQ,CAAU;CACnB;AALD,gCAKC;AAED,SAAS,eAAe,CAAC,KAAa;IACpC,IAAI,CAAC,IAAA,gCAAe,EAAC,KAAK,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;QACjD,MAAM,IAAI,KAAK,CACb,6BAA6B,KAAK,KAAK;YACrC,4DAA4D,CAC/D,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,mBAAmB,CAAC,KAAK,GAAG,OAAO;IACjD,MAAM,IAAI,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,iBAAiB,CAAC;IACxE,OAAO,8BAA8B,IAAI;;;;;;6BAMd,KAAK,OAAO,IAAI,gBAAgB,CAAC;AAC9D,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,sBAAsB,CACpC,KAAK,GAAG,OAAO;IAEf,MAAM,IAAI,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,iBAAiB,CAAC;IACxE,OAAO,IAAI,mBAAY,CAAa;QAClC,KAAK,EAAE,UAAU;QACjB,SAAS,EAAE,IAAI;QACf,UAAU,EAAE;YACV,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE;YACnD,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE;YACvB,SAAS,EAAE;gBACT,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE,QAAQ;gBACpB,SAAS,EAAE,YAAY;gBACvB,QAAQ,EAAE,IAAI;aACf;YACD,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,EAAE;SAChE;QACD,OAAO,EAAE;YACP;gBACE,IAAI,EAAE,KAAK;gBACX,UAAU,EAAE,CAAC,WAAW,CAAC;aAC1B;SACF;KACF,CAAC,CAAC;AACL,CAAC;AAED,oEAAoE;AACvD,QAAA,gBAAgB,GAAG,sBAAsB,EAAE,CAAC"}
@@ -0,0 +1,82 @@
1
+ import { type CacheFillOptions, type CacheSetOptions, type CacheStateEntry, type IVersionedCache } from '@cqrs-ddd/core/application';
2
+ import type { ICacheLogger } from '@cqrs-ddd/core/persistence';
3
+ import type { EntityManager } from '@mikro-orm/core';
4
+ import type { IEntityManagerSource } from '../interfaces/entity-manager-source';
5
+ /**
6
+ * An {@link IEntityManagerSource} that can also run work in a transaction.
7
+ *
8
+ * `transactional` must run `work` on a manager dedicated to that call, never on
9
+ * the caller's request or transaction manager, so the cache's compare-and-set
10
+ * steps commit on their own and never join a surrounding unit of work.
11
+ * `em.fork().transactional(work)` satisfies it.
12
+ */
13
+ export interface ITransactionalEntityManagerSource extends IEntityManagerSource {
14
+ transactional<T>(work: (em: EntityManager) => Promise<T>): Promise<T>;
15
+ }
16
+ /** Options for {@link MikroOrmCache}. */
17
+ export interface MikroOrmCacheOptions {
18
+ /** Time to live in milliseconds when a write passes none; `0` never expires. Default 60,000. */
19
+ readonly defaultTtlMs?: number;
20
+ /**
21
+ * Receives cache-maintenance warnings. Defaults to `console.warn` with a
22
+ * `[MikroOrmCache]` prefix. See {@link ICacheLogger}.
23
+ */
24
+ readonly logger?: ICacheLogger;
25
+ }
26
+ /**
27
+ * MikroORM-backed {@link IVersionedCache}: one row per key in the table mapped by
28
+ * {@link CacheEntrySchema} (or {@link createCacheEntrySchema}).
29
+ *
30
+ * Implements {@link IVersionedCache} with revision-fenced atomic coordination,
31
+ * bypassing the identity map across all read and mutation operations. Reads use
32
+ * `store.em`; every write runs in `store.transactional(...)`.
33
+ *
34
+ * A plain class with no framework dependency. In a NestJS application, register
35
+ * it with a factory:
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * {
40
+ * provide: CACHE_TOKEN,
41
+ * useFactory: (store: AppStore) =>
42
+ * new MikroOrmCache(store, { logger: new Logger('MikroOrmCache') }),
43
+ * inject: [STORE],
44
+ * }
45
+ * ```
46
+ */
47
+ export declare class MikroOrmCache<T> implements IVersionedCache<T> {
48
+ private readonly store;
49
+ readonly isVersioned: true;
50
+ private readonly logger;
51
+ private readonly defaultTtlMs;
52
+ constructor(store: ITransactionalEntityManagerSource, options?: MikroOrmCacheOptions);
53
+ /**
54
+ * Observes the current key state and its revision token.
55
+ * Reads bypass the identity map to guarantee authoritative persistence visibility.
56
+ */
57
+ readState(key: string): Promise<CacheStateEntry<T>>;
58
+ /**
59
+ * Atomically advances the revision for `key` and evicts the payload value.
60
+ * Retains the entry to prevent ABA races during concurrent fills.
61
+ */
62
+ invalidate(key: string): Promise<string>;
63
+ /**
64
+ * Atomically checks that current revision matches `observedRevision`, writes
65
+ * value, and advances revision on match.
66
+ */
67
+ tryFill(key: string, observedRevision: string, value: T, options?: CacheFillOptions): Promise<boolean>;
68
+ /**
69
+ * Get a value from the cache by key. Handles TTL expiry and returns detached clone.
70
+ */
71
+ get(key: string): Promise<T | undefined>;
72
+ /**
73
+ * Stores a value in the relational cache table with transactional CAS concurrency safety.
74
+ */
75
+ set(key: string, value: T, options?: CacheSetOptions): Promise<void>;
76
+ /**
77
+ * Removes the value and advances the key's revision, as invalidate() does; the
78
+ * row is kept.
79
+ */
80
+ delete(key: string): Promise<void>;
81
+ }
82
+ //# sourceMappingURL=mikro-orm.cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mikro-orm.cache.d.ts","sourceRoot":"","sources":["../../src/cache/mikro-orm.cache.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAehF;;;;;;;GAOG;AACH,MAAM,WAAW,iCACf,SAAQ,oBAAoB;IAC5B,aAAa,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,aAAa,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACvE;AAED,yCAAyC;AACzC,MAAM,WAAW,oBAAoB;IACnC,gGAAgG;IAChG,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;CAChC;AAmBD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,aAAa,CAAC,CAAC,CAAE,YAAW,eAAe,CAAC,CAAC,CAAC;IAOvD,OAAO,CAAC,QAAQ,CAAC,KAAK;IANxB,QAAQ,CAAC,WAAW,EAAG,IAAI,CAAU;IAErC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IACtC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;gBAGnB,KAAK,EAAE,iCAAiC,EACzD,OAAO,CAAC,EAAE,oBAAoB;IAMhC;;;OAGG;IACG,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;IA4BzD;;;OAGG;IACG,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAyC9C;;;OAGG;IACG,OAAO,CACX,GAAG,EAAE,MAAM,EACX,gBAAgB,EAAE,MAAM,EACxB,KAAK,EAAE,CAAC,EACR,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,OAAO,CAAC;IAqDnB;;OAEG;IACG,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC;IAK9C;;OAEG;IACG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAwD1E;;;OAGG;IACG,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAGzC"}