@decohere/data-mikro-orm 0.0.0-stage → 0.0.1-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -2
- package/package.json +40 -4
- package/src/index.ts +3 -0
- package/src/inject-mikro-orm.ts +23 -0
- package/src/mikro-orm.module.ts +147 -0
- package/src/mikro-orm.unit-of-work.ts +163 -0
- package/tests/mikro-orm.module.spec.ts +37 -0
- package/tests/mikro-orm.plugin.docker.spec.ts +138 -0
package/README.md
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @decohere/data-mikro-orm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The MikroORM provider for [`@decohere/data`](../data/README.md): data's `IUnitOfWork` over MikroORM's own unit of work. MikroORM tracks the changes, keeps the identity map and orders the writes. This package adds Decohere's `Query<T>`, the outbox, and one rule: nothing is written before `commit()`. Each unit of work forks the entity manager with `flushMode: "commit"`, so a query never flushes pending changes.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { mikroOrm } from "@decohere/data-mikro-orm";
|
|
7
|
+
|
|
8
|
+
builder.use(mikroOrm({ entities: [OrderSchema, LineSchema], repositories: [OrderRepository], outbox: toOutboxMessage }));
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`mikroOrm()` reads the `database` config section, like `typeOrm()`. For each data source it:
|
|
12
|
+
|
|
13
|
+
- bootstraps the database, least-privilege roles and schema when the config asks (`@decohere/data/postgres`);
|
|
14
|
+
- opens one MikroORM instance as the app role, named for the app in `application_name`;
|
|
15
|
+
- creates missing tables when `synchronize` is on (development only), never dropping any;
|
|
16
|
+
- runs `seed(orm)` when `seed` is on;
|
|
17
|
+
- registers a unit of work per request (`@injectUnitOfWork()`), the instance itself (`@injectMikroOrm()`) and a readiness check.
|
|
18
|
+
|
|
19
|
+
The container closes the instance when the app stops, after hosted services. Postgres only. Outside a plugin, `new MikroOrmUnitOfWork(orm.em, { outbox })` gives the same unit of work.
|
|
20
|
+
|
|
21
|
+
Map domain classes with `defineEntity({ class, … })` in infrastructure files, so the domain imports nothing from MikroORM. Map each child collection as a one-to-many with `orphanRemoval()`, so a child dropped from its aggregate is deleted.
|
|
22
|
+
|
|
23
|
+
Things to know:
|
|
24
|
+
|
|
25
|
+
- **MikroORM changes the classes it maps** at run time: field accessors, `toJSON` and a `__helper`. A loaded child also carries its parent. Map HTTP responses to DTOs rather than serialising entities. Don't map one class with two providers in one process.
|
|
26
|
+
- **Version fields** need a database default (`version int not null default 1`). MikroORM leaves the column to it on insert.
|
|
27
|
+
- **SQL a query can't express:** `uow.entityManager.getKysely()`, inside a repository.
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decohere/data-mikro-orm",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1-dev.5",
|
|
4
|
+
"description": "MikroORM provider for @decohere/data: its own unit of work under data's contracts",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"typescript",
|
|
7
|
+
"mikro-orm",
|
|
8
|
+
"postgres",
|
|
9
|
+
"data-access",
|
|
10
|
+
"decohere"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/typesmiths/decohere/tree/main/projects/data/data-mikro-orm#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/typesmiths/decohere/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/typesmiths/decohere.git",
|
|
19
|
+
"directory": "projects/data/data-mikro-orm"
|
|
20
|
+
},
|
|
21
|
+
"license": "ISC",
|
|
22
|
+
"author": "Typesmiths",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./types/src/index.d.ts",
|
|
27
|
+
"import": "./es6/src/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@decohere/core": "0.0.1-dev.5",
|
|
35
|
+
"@decohere/crucible": "0.0.1-dev.5",
|
|
36
|
+
"@decohere/data": "0.0.1-dev.5",
|
|
37
|
+
"@decohere/scribe": "0.0.1-dev.5",
|
|
38
|
+
"@mikro-orm/core": "^7.2.8",
|
|
39
|
+
"@mikro-orm/postgresql": "^7.2.8"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {}
|
|
42
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { DEFAULT_DATA_SOURCE } from "@decohere/data";
|
|
2
|
+
import { inject } from "@decohere/crucible/decorators";
|
|
3
|
+
|
|
4
|
+
/** The MikroORM instance when `mikroOrm()` is used without `name`. */
|
|
5
|
+
export const MikroOrmToken = Symbol("MikroORM");
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Container key for a data source's MikroORM instance. Distinct from the unit of work's key
|
|
9
|
+
* (the data source's name, or {@link DEFAULT_DATA_SOURCE}): the instance lives as long as the
|
|
10
|
+
* app, a unit of work as long as a request.
|
|
11
|
+
*/
|
|
12
|
+
export function mikroOrmToken(name?: string | symbol): symbol {
|
|
13
|
+
if (name == null || name === DEFAULT_DATA_SOURCE) return MikroOrmToken;
|
|
14
|
+
return Symbol.for(`decohere:mikro-orm:${String(name)}`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Inject the MikroORM instance, for work that outlives a request. Pass the same `name` as
|
|
19
|
+
* `mikroOrm({ name })`. Request work should use `injectUnitOfWork`.
|
|
20
|
+
*/
|
|
21
|
+
export function injectMikroOrm(name?: string | symbol) {
|
|
22
|
+
return inject(mikroOrmToken(name));
|
|
23
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { BuilderPlugin } from "@decohere/core/hosting";
|
|
2
|
+
import { type IReadinessCheck, ReadinessCheckToken } from "@decohere/core/hosting";
|
|
3
|
+
import type { Constructable } from "@decohere/core/reflection";
|
|
4
|
+
import type { ContainerBuilder } from "@decohere/crucible";
|
|
5
|
+
import {
|
|
6
|
+
type ConnectionInfo,
|
|
7
|
+
DatabaseConfig,
|
|
8
|
+
DataConfigurationError,
|
|
9
|
+
dataSources,
|
|
10
|
+
type OutboxMapper,
|
|
11
|
+
} from "@decohere/data";
|
|
12
|
+
import { bootstrapDataSources } from "@decohere/data/postgres";
|
|
13
|
+
import { scribe } from "@decohere/scribe";
|
|
14
|
+
import { type Options, MikroORM } from "@mikro-orm/postgresql";
|
|
15
|
+
import { mikroOrmToken } from "./inject-mikro-orm.js";
|
|
16
|
+
import { MikroOrmUnitOfWork } from "./mikro-orm.unit-of-work.js";
|
|
17
|
+
|
|
18
|
+
export type MikroOrmModuleConfig = {
|
|
19
|
+
/** The data source's name in the `database` config. Required when there is more than one. */
|
|
20
|
+
name?: string | symbol;
|
|
21
|
+
/** The mappings: `defineEntity({ class, … })` results or `EntitySchema`s. */
|
|
22
|
+
entities: NonNullable<Options["entities"]>;
|
|
23
|
+
repositories?: Constructable[];
|
|
24
|
+
/** Writes the events aggregates raise to an outbox entity, in the same commit. */
|
|
25
|
+
outbox?: OutboxMapper;
|
|
26
|
+
/** Runs after connecting when the data source's `seed` is on. */
|
|
27
|
+
seed?: (orm: MikroORM) => Promise<void>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export type MikroOrmModuleOptions = {
|
|
31
|
+
applicationName: string;
|
|
32
|
+
databaseConfig: DatabaseConfig;
|
|
33
|
+
moduleConfigurations: MikroOrmModuleConfig[];
|
|
34
|
+
containerBuilder: ContainerBuilder;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export class MikroOrmModule {
|
|
38
|
+
/** Bootstraps and opens a MikroORM instance per data source. Returns the names it registered them under. */
|
|
39
|
+
public async configure(options: MikroOrmModuleOptions): Promise<(string | symbol)[]> {
|
|
40
|
+
const { applicationName, databaseConfig, moduleConfigurations, containerBuilder } =
|
|
41
|
+
options;
|
|
42
|
+
const resolved = dataSources.resolve(databaseConfig, moduleConfigurations);
|
|
43
|
+
// Once, before any instance connects: data sources sharing a database must not race to create it.
|
|
44
|
+
await bootstrapDataSources(
|
|
45
|
+
resolved.map((r) => r.connectionInfo),
|
|
46
|
+
{ applicationName },
|
|
47
|
+
);
|
|
48
|
+
return Promise.all(
|
|
49
|
+
resolved.map(async ({ name, connectionInfo, module }) => {
|
|
50
|
+
const orm = await this.open(applicationName, name, connectionInfo, module);
|
|
51
|
+
containerBuilder.registerSingleton(mikroOrmToken(name), orm);
|
|
52
|
+
containerBuilder.registerRequestScoped(
|
|
53
|
+
name,
|
|
54
|
+
() => new MikroOrmUnitOfWork(orm.em, { outbox: module.outbox }),
|
|
55
|
+
);
|
|
56
|
+
containerBuilder.registerSingleton(ReadinessCheckToken, readinessCheck(name, orm));
|
|
57
|
+
for (const repository of module.repositories ?? []) {
|
|
58
|
+
containerBuilder.registerRequestScoped(repository);
|
|
59
|
+
}
|
|
60
|
+
return name;
|
|
61
|
+
}),
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
private async open(
|
|
66
|
+
applicationName: string,
|
|
67
|
+
name: string | symbol,
|
|
68
|
+
connection: ConnectionInfo,
|
|
69
|
+
module: MikroOrmModuleConfig,
|
|
70
|
+
): Promise<MikroORM> {
|
|
71
|
+
if (connection.provider !== "postgres") {
|
|
72
|
+
throw new DataConfigurationError(
|
|
73
|
+
`Data source ${connection.name}: the MikroORM provider supports postgres, not ${connection.provider}`,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
const log = scribe.logger(`MikroORM:${String(name)}`);
|
|
77
|
+
const orm = await MikroORM.init({
|
|
78
|
+
host: connection.host,
|
|
79
|
+
port: connection.port,
|
|
80
|
+
dbName: connection.database,
|
|
81
|
+
user: connection.username,
|
|
82
|
+
password: connection.password,
|
|
83
|
+
schema: connection.schema,
|
|
84
|
+
entities: module.entities,
|
|
85
|
+
driverOptions: { application_name: applicationName },
|
|
86
|
+
debug: ["query", "query-params"],
|
|
87
|
+
logger: (message) => log.debug(message),
|
|
88
|
+
});
|
|
89
|
+
if (connection.synchronize) await synchronize(orm);
|
|
90
|
+
if (connection.seed) await module.seed?.(orm);
|
|
91
|
+
return orm;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Bring the tables up to the mappings, safely: add what they need, never drop what they don't name.
|
|
97
|
+
* MikroORM starts the update with `create schema`, which the app role may not run even when the
|
|
98
|
+
* schema exists; the bootstrap creates schemas, so those statements are left out.
|
|
99
|
+
*/
|
|
100
|
+
async function synchronize(orm: MikroORM) {
|
|
101
|
+
const sql = await orm.schema.getUpdateSchemaSQL({
|
|
102
|
+
safe: true,
|
|
103
|
+
dropTables: false,
|
|
104
|
+
wrap: false,
|
|
105
|
+
});
|
|
106
|
+
const statements = sql
|
|
107
|
+
.split(/;\n/)
|
|
108
|
+
.map((statement) => statement.trim().replace(/;$/, ""))
|
|
109
|
+
.filter((statement) => statement.length > 0 && !/^create schema\b/i.test(statement));
|
|
110
|
+
for (const statement of statements) await orm.schema.execute(statement);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function readinessCheck(name: string | symbol, orm: MikroORM): IReadinessCheck {
|
|
114
|
+
return {
|
|
115
|
+
name: `mikro-orm:${String(name)}`,
|
|
116
|
+
async check() {
|
|
117
|
+
const status = await orm.checkConnection();
|
|
118
|
+
if ("reason" in status) throw new Error(status.reason, { cause: status.error });
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Connect to the databases in the `database` config section with MikroORM. Requires `config(...)` on the builder. */
|
|
124
|
+
export function mikroOrm(
|
|
125
|
+
config: MikroOrmModuleConfig[] | MikroOrmModuleConfig,
|
|
126
|
+
): BuilderPlugin {
|
|
127
|
+
return (builder) => {
|
|
128
|
+
const names: (string | symbol)[] = [];
|
|
129
|
+
builder.registerPreBuildStep(async (configService, containerBuilder) => {
|
|
130
|
+
const databaseConfig = await configService.get(DatabaseConfig);
|
|
131
|
+
names.push(
|
|
132
|
+
...(await new MikroOrmModule().configure({
|
|
133
|
+
applicationName: builder.applicationName,
|
|
134
|
+
databaseConfig,
|
|
135
|
+
moduleConfigurations: Array.isArray(config) ? config : [config],
|
|
136
|
+
containerBuilder,
|
|
137
|
+
})),
|
|
138
|
+
);
|
|
139
|
+
});
|
|
140
|
+
// The container disposes only what it handed out. Resolving each instance here makes the
|
|
141
|
+
// root container own it, as one of its first, so it closes last: after hosted services
|
|
142
|
+
// and the services that use it.
|
|
143
|
+
builder.registerPostBuildStep((container) => {
|
|
144
|
+
for (const name of names) container.resolve(mikroOrmToken(name));
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import {
|
|
2
|
+
comparison,
|
|
3
|
+
DataError,
|
|
4
|
+
domainEvents,
|
|
5
|
+
type EntityClass,
|
|
6
|
+
type EntityKey,
|
|
7
|
+
type Include,
|
|
8
|
+
type IUnitOfWork,
|
|
9
|
+
OptimisticLockError,
|
|
10
|
+
type OutboxMapper,
|
|
11
|
+
type Query,
|
|
12
|
+
type Where,
|
|
13
|
+
} from "@decohere/data";
|
|
14
|
+
import {
|
|
15
|
+
type EntityManager,
|
|
16
|
+
type EntityName,
|
|
17
|
+
type FilterQuery,
|
|
18
|
+
type FindOptions,
|
|
19
|
+
FlushMode,
|
|
20
|
+
LockMode,
|
|
21
|
+
OptimisticLockError as MikroOptimisticLockError,
|
|
22
|
+
} from "@mikro-orm/core";
|
|
23
|
+
|
|
24
|
+
export type MikroOrmUnitOfWorkOptions = {
|
|
25
|
+
/** Writes the events aggregates raise to an outbox entity, in the same commit. */
|
|
26
|
+
outbox?: OutboxMapper;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The MikroORM provider: data's unit of work over MikroORM's own. MikroORM tracks the changes,
|
|
31
|
+
* keeps the identity map and orders the writes; this adds Decohere's query, the outbox, and
|
|
32
|
+
* one rule: nothing is written before {@link commit}, so the entity manager never auto-flushes.
|
|
33
|
+
*/
|
|
34
|
+
export class MikroOrmUnitOfWork implements IUnitOfWork {
|
|
35
|
+
private readonly em: EntityManager;
|
|
36
|
+
private failure: unknown;
|
|
37
|
+
private disposed = false;
|
|
38
|
+
|
|
39
|
+
/** @param em the application's entity manager; each unit of work forks its own. */
|
|
40
|
+
public constructor(
|
|
41
|
+
em: EntityManager,
|
|
42
|
+
private readonly options: MikroOrmUnitOfWorkOptions = {},
|
|
43
|
+
) {
|
|
44
|
+
this.em = em.fork({ clear: true, flushMode: FlushMode.COMMIT });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The entity manager behind this unit of work, for SQL a query can't express (`em.getKysely()`), inside a repository. */
|
|
48
|
+
public get entityManager(): EntityManager {
|
|
49
|
+
return this.em;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public findById<T extends object>(
|
|
53
|
+
type: EntityClass<T>,
|
|
54
|
+
key: EntityKey<T>,
|
|
55
|
+
include: readonly Include<T>[] = [],
|
|
56
|
+
): Promise<T | null> {
|
|
57
|
+
this.assertUsable();
|
|
58
|
+
const where = (
|
|
59
|
+
key !== null && typeof key === "object" ? toFilter(key as Where<T>) : key
|
|
60
|
+
) as FilterQuery<T>;
|
|
61
|
+
return this.em.findOne(entityName(type), where, { populate: include } as FindOptions<T>);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
public async find<T extends object>(
|
|
65
|
+
type: EntityClass<T>,
|
|
66
|
+
query: Query<T> = {},
|
|
67
|
+
): Promise<T[]> {
|
|
68
|
+
this.assertUsable();
|
|
69
|
+
if (query.lock && !this.em.isInTransaction()) await this.em.begin();
|
|
70
|
+
const options = {
|
|
71
|
+
orderBy: query.orderBy,
|
|
72
|
+
limit: query.limit,
|
|
73
|
+
populate: query.include ?? [],
|
|
74
|
+
...(query.lock ? { lockMode: LockMode.PESSIMISTIC_WRITE } : {}),
|
|
75
|
+
} as FindOptions<T>;
|
|
76
|
+
return this.em.find(
|
|
77
|
+
entityName(type),
|
|
78
|
+
toFilter(query.where ?? {}) as FilterQuery<T>,
|
|
79
|
+
options,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
public async findOne<T extends object>(type: EntityClass<T>, query: Query<T> = {}) {
|
|
84
|
+
const [found] = await this.find(type, { ...query, limit: 1 });
|
|
85
|
+
return found ?? null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
public add(entity: object) {
|
|
89
|
+
this.assertUsable();
|
|
90
|
+
this.em.persist(entity);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
public remove(entity: object) {
|
|
94
|
+
this.assertUsable();
|
|
95
|
+
this.em.remove(entity);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
public async beginTransaction() {
|
|
99
|
+
this.assertUsable();
|
|
100
|
+
if (!this.em.isInTransaction()) await this.em.begin();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
public async commit() {
|
|
104
|
+
this.assertUsable();
|
|
105
|
+
try {
|
|
106
|
+
if (this.options.outbox) {
|
|
107
|
+
const uow = this.em.getUnitOfWork();
|
|
108
|
+
const entities = [...uow.getIdentityMap().values(), ...uow.getPersistStack()];
|
|
109
|
+
for (const row of domainEvents.collect(entities, this.options.outbox))
|
|
110
|
+
this.em.persist(row);
|
|
111
|
+
}
|
|
112
|
+
// em.commit() flushes, then commits; outside a transaction, flush opens and commits its own.
|
|
113
|
+
if (this.em.isInTransaction()) await this.em.commit();
|
|
114
|
+
else await this.em.flush();
|
|
115
|
+
} catch (err) {
|
|
116
|
+
this.failure = err;
|
|
117
|
+
if (this.em.isInTransaction()) await this.em.rollback();
|
|
118
|
+
if (err instanceof MikroOptimisticLockError) {
|
|
119
|
+
throw new OptimisticLockError(err.message, { cause: err });
|
|
120
|
+
}
|
|
121
|
+
throw err;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
public async [Symbol.asyncDispose]() {
|
|
126
|
+
if (this.disposed) return;
|
|
127
|
+
this.disposed = true;
|
|
128
|
+
try {
|
|
129
|
+
if (this.em.isInTransaction()) await this.em.rollback();
|
|
130
|
+
} finally {
|
|
131
|
+
this.em.clear();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private assertUsable() {
|
|
136
|
+
if (this.disposed) throw new DataError("This unit of work was disposed");
|
|
137
|
+
if (this.failure !== undefined) {
|
|
138
|
+
throw new DataError(
|
|
139
|
+
"A commit failed in this unit of work, so it was rolled back: start a new one",
|
|
140
|
+
{
|
|
141
|
+
cause: this.failure,
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Decohere's entity class as MikroORM names it. The two describe the same constructor. */
|
|
149
|
+
function entityName<T extends object>(type: EntityClass<T>): EntityName<T> {
|
|
150
|
+
return type as unknown as EntityName<T>;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Decohere's conditions in MikroORM's operators: `{ in: [...] }` becomes `{ $in: [...] }`. */
|
|
154
|
+
function toFilter(where: Record<string, unknown>): Record<string, unknown> {
|
|
155
|
+
return Object.fromEntries(
|
|
156
|
+
Object.entries(where).map(([prop, condition]) => {
|
|
157
|
+
const operator = comparison.operatorOf(condition);
|
|
158
|
+
if (!operator) return [prop, condition];
|
|
159
|
+
const [op, operand] = operator;
|
|
160
|
+
return [prop, { [`$${op}`]: operand }];
|
|
161
|
+
}),
|
|
162
|
+
);
|
|
163
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ServiceContainerBuilder } from "@decohere/crucible";
|
|
2
|
+
import { DataConfigurationError, DatabaseConfig } from "@decohere/data";
|
|
3
|
+
import { describe, expect, it } from "vitest";
|
|
4
|
+
import { MikroOrmModule } from "../src/mikro-orm.module.js";
|
|
5
|
+
|
|
6
|
+
describe("MikroOrmModule", () => {
|
|
7
|
+
it("refuses a data source that isn't Postgres, naming it", async () => {
|
|
8
|
+
const databaseConfig = new DatabaseConfig();
|
|
9
|
+
databaseConfig.dataSources = [
|
|
10
|
+
{
|
|
11
|
+
name: "reports",
|
|
12
|
+
provider: "mssql",
|
|
13
|
+
host: "127.0.0.1",
|
|
14
|
+
port: 1433,
|
|
15
|
+
database: "reports",
|
|
16
|
+
username: "app",
|
|
17
|
+
password: "secret",
|
|
18
|
+
synchronize: false,
|
|
19
|
+
seed: false,
|
|
20
|
+
bootstrap: false,
|
|
21
|
+
},
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
await expect(
|
|
25
|
+
new MikroOrmModule().configure({
|
|
26
|
+
applicationName: "reports.api",
|
|
27
|
+
databaseConfig,
|
|
28
|
+
moduleConfigurations: [{ entities: [] }],
|
|
29
|
+
containerBuilder: new ServiceContainerBuilder(),
|
|
30
|
+
}),
|
|
31
|
+
).rejects.toThrow(
|
|
32
|
+
new DataConfigurationError(
|
|
33
|
+
"Data source reports: the MikroORM provider supports postgres, not mssql",
|
|
34
|
+
),
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// mikroOrm() in a running app, against Postgres, the way a generated app uses it in development:
|
|
2
|
+
// it bootstraps the database and roles, creates the tables, seeds, gives each request its own
|
|
3
|
+
// unit of work, reports ready, and closes when the app stops. Needs Docker: `pnpm test:docker`.
|
|
4
|
+
import "reflect-metadata";
|
|
5
|
+
import { Builder, type BuilderPlugin } from "@decohere/core/hosting";
|
|
6
|
+
import {
|
|
7
|
+
ConfigurationServiceToken,
|
|
8
|
+
type IConfigurationService,
|
|
9
|
+
} from "@decohere/core/configuration";
|
|
10
|
+
import type { IContainer } from "@decohere/core/composition";
|
|
11
|
+
import type { Constructable } from "@decohere/core/reflection";
|
|
12
|
+
import { ServiceContainerBuilder } from "@decohere/crucible";
|
|
13
|
+
import {
|
|
14
|
+
type ConnectionInfo,
|
|
15
|
+
DatabaseConfig,
|
|
16
|
+
DEFAULT_DATA_SOURCE,
|
|
17
|
+
type IUnitOfWork,
|
|
18
|
+
} from "@decohere/data";
|
|
19
|
+
import { defineEntity, p } from "@mikro-orm/core";
|
|
20
|
+
import type { MikroORM } from "@mikro-orm/postgresql";
|
|
21
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
22
|
+
import {
|
|
23
|
+
type PostgresContainer,
|
|
24
|
+
startPostgres,
|
|
25
|
+
} from "../../data/tests/postgres/postgres-container.js";
|
|
26
|
+
import { mikroOrm, MikroOrmToken } from "../src/index.js";
|
|
27
|
+
|
|
28
|
+
class Note {
|
|
29
|
+
public id!: number;
|
|
30
|
+
public constructor(public text: string) {}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const NoteSchema = defineEntity({
|
|
34
|
+
class: Note,
|
|
35
|
+
tableName: "note",
|
|
36
|
+
properties: { id: p.integer().primary().autoincrement(), text: p.text() },
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
class StaticConfig implements IConfigurationService {
|
|
40
|
+
public readonly dataSources = [];
|
|
41
|
+
public constructor(private readonly connection: ConnectionInfo) {}
|
|
42
|
+
public async get<T extends object>(type: Constructable<T> | string): Promise<T> {
|
|
43
|
+
const config = new DatabaseConfig();
|
|
44
|
+
if (type === DatabaseConfig) config.dataSources = [this.connection];
|
|
45
|
+
return config as unknown as T;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The app's container, which App keeps to itself, caught the way a plugin sees it. */
|
|
50
|
+
function containerOf() {
|
|
51
|
+
let container: IContainer;
|
|
52
|
+
const plugin: BuilderPlugin = (builder) =>
|
|
53
|
+
builder.registerPostBuildStep((c) => {
|
|
54
|
+
container = c;
|
|
55
|
+
});
|
|
56
|
+
return { plugin, get: () => container };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe("mikroOrm() in an app", () => {
|
|
60
|
+
let postgres: PostgresContainer;
|
|
61
|
+
|
|
62
|
+
beforeAll(async () => {
|
|
63
|
+
// Bootstrap and synchronize are for development only, and refuse to run elsewhere.
|
|
64
|
+
vi.stubEnv("NODE_ENV", "development");
|
|
65
|
+
postgres = await startPostgres();
|
|
66
|
+
await postgres.superuser.query(
|
|
67
|
+
"CREATE ROLE decohere_bootstrap LOGIN PASSWORD 'bootstrap-pw' CREATEDB CREATEROLE NOSUPERUSER NOBYPASSRLS",
|
|
68
|
+
);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
afterAll(async () => {
|
|
72
|
+
vi.unstubAllEnvs();
|
|
73
|
+
await postgres?.stop();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("bootstraps, creates tables, seeds, and gives each request its own unit of work", async () => {
|
|
77
|
+
const connection: ConnectionInfo = {
|
|
78
|
+
name: "notes",
|
|
79
|
+
provider: "postgres",
|
|
80
|
+
host: postgres.host,
|
|
81
|
+
port: postgres.port,
|
|
82
|
+
database: "notes_dev",
|
|
83
|
+
username: "notes_app",
|
|
84
|
+
password: "app-pw",
|
|
85
|
+
schema: "notes",
|
|
86
|
+
synchronize: true,
|
|
87
|
+
seed: true,
|
|
88
|
+
bootstrap: true,
|
|
89
|
+
adminUser: "decohere_bootstrap",
|
|
90
|
+
adminPassword: "bootstrap-pw",
|
|
91
|
+
migrateUsername: "notes_migrate",
|
|
92
|
+
migratePassword: "migrate-pw",
|
|
93
|
+
};
|
|
94
|
+
const probe = containerOf();
|
|
95
|
+
const app = await Builder.create(new ServiceContainerBuilder(), {
|
|
96
|
+
applicationName: "notes.api",
|
|
97
|
+
})
|
|
98
|
+
.withServices((c) =>
|
|
99
|
+
c.registerSingleton(ConfigurationServiceToken, new StaticConfig(connection)),
|
|
100
|
+
)
|
|
101
|
+
.use(
|
|
102
|
+
mikroOrm({
|
|
103
|
+
entities: [NoteSchema],
|
|
104
|
+
seed: async (orm) => {
|
|
105
|
+
const em = orm.em.fork();
|
|
106
|
+
await em.persist(new Note("seeded")).flush();
|
|
107
|
+
},
|
|
108
|
+
}),
|
|
109
|
+
)
|
|
110
|
+
.use(probe.plugin)
|
|
111
|
+
.build();
|
|
112
|
+
|
|
113
|
+
{
|
|
114
|
+
await using scope = probe.get().beginScope("first request");
|
|
115
|
+
const uow = scope.resolve<IUnitOfWork>(DEFAULT_DATA_SOURCE);
|
|
116
|
+
expect(scope.resolve(DEFAULT_DATA_SOURCE)).toBe(uow);
|
|
117
|
+
uow.add(new Note("from a request"));
|
|
118
|
+
await uow.commit();
|
|
119
|
+
}
|
|
120
|
+
{
|
|
121
|
+
await using scope = probe.get().beginScope("second request");
|
|
122
|
+
const uow = scope.resolve<IUnitOfWork>(DEFAULT_DATA_SOURCE);
|
|
123
|
+
const notes = await uow.find(Note, { orderBy: { id: "asc" } });
|
|
124
|
+
expect(notes.map((n) => n.text)).toEqual(["seeded", "from a request"]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const orm = probe.get().resolve<MikroORM>(MikroOrmToken);
|
|
128
|
+
const [who] = await orm.em
|
|
129
|
+
.getConnection()
|
|
130
|
+
.execute<{ user: string; app: string }[]>(
|
|
131
|
+
"select current_user as user, current_setting('application_name') as app",
|
|
132
|
+
);
|
|
133
|
+
expect(who).toEqual({ user: "notes_app", app: "notes.api" });
|
|
134
|
+
|
|
135
|
+
await app.dispose();
|
|
136
|
+
expect(await orm.isConnected()).toBe(false);
|
|
137
|
+
});
|
|
138
|
+
});
|