@decohere/data-memory 0.0.1-dev.20261122.343 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decohere/data-memory",
3
- "version": "0.0.1-dev.20261122.343",
3
+ "version": "0.0.1-dev.5",
4
4
  "description": "In-memory provider for @decohere/data: repositories and the unit of work with no database, for tests and local runs",
5
5
  "keywords": [
6
6
  "typescript",
@@ -31,8 +31,8 @@
31
31
  "test": "echo \"Error: no test specified\" && exit 1"
32
32
  },
33
33
  "dependencies": {
34
- "@decohere/core": "0.0.1-dev.20261122.343",
35
- "@decohere/data": "0.0.1-dev.20261122.343"
34
+ "@decohere/core": "0.0.1-dev.5",
35
+ "@decohere/data": "0.0.1-dev.5"
36
36
  },
37
37
  "devDependencies": {}
38
38
  }
@@ -0,0 +1,150 @@
1
+ import {
2
+ type ChildKeys,
3
+ type ChildrenModel,
4
+ DataConfigurationError,
5
+ type EntityClass,
6
+ type EntityModel,
7
+ type FieldKeys,
8
+ type ReferenceModel,
9
+ } from "@decohere/data";
10
+
11
+ /** A reference to another mapped class, stored as that class's key. */
12
+ export type MemoryReference<T> = {
13
+ prop: FieldKeys<T>;
14
+ target: EntityClass;
15
+ /** Whether it may be empty. Defaults to false: a row can't be written without it. */
16
+ nullable?: boolean;
17
+ /** `"cascade"`: deleting the referenced row deletes this one, like `ON DELETE CASCADE`. Otherwise the delete fails while this row references it. */
18
+ onDelete?: "cascade";
19
+ };
20
+
21
+ /** A child collection: the rows of `target` whose `parentRef` references this one. */
22
+ export type MemoryChildren<T> = {
23
+ prop: ChildKeys<T>;
24
+ target: EntityClass;
25
+ /** The child's reference to its parent. */
26
+ parentRef: string;
27
+ /** The order children load in. Defaults to the child's key, ascending. */
28
+ orderBy?: Record<string, "asc" | "desc">;
29
+ };
30
+
31
+ export type MemoryEntityOptions<T> = {
32
+ /** The properties making the key: fields or references. Defaults to `["id"]`. */
33
+ key?: FieldKeys<T>[];
34
+ /** The properties stored as values. Key fields, the version and the generated key may be left out. */
35
+ fields: FieldKeys<T>[];
36
+ references?: MemoryReference<T>[];
37
+ children?: MemoryChildren<T>[];
38
+ /** A number checked and incremented on every update. */
39
+ version?: FieldKeys<T>;
40
+ /** A key field the store numbers 1, 2, 3… when an insert leaves it empty, like a serial column. */
41
+ generated?: FieldKeys<T>;
42
+ };
43
+
44
+ /** One class's mapping, as {@link mapEntity} makes it. */
45
+ export type MemoryEntity = EntityModel & {
46
+ references: (ReferenceModel & { onDelete?: "cascade" })[];
47
+ generated?: string;
48
+ };
49
+
50
+ /**
51
+ * Map a class for the memory provider. With no ORM to read metadata from, the mapping is written
52
+ * out: which properties are stored, which reference another class, and which hold children.
53
+ */
54
+ export function mapEntity<T extends object>(
55
+ type: EntityClass<T>,
56
+ options: MemoryEntityOptions<T>,
57
+ ): MemoryEntity {
58
+ const key: string[] = options.key ?? ["id"];
59
+ const references = (options.references ?? []).map((r) => ({
60
+ prop: r.prop,
61
+ target: r.target,
62
+ nullable: r.nullable ?? false,
63
+ onDelete: r.onDelete,
64
+ }));
65
+ const isReference = (prop: string) => references.some((r) => r.prop === prop);
66
+ const fields = new Set<string>(options.fields);
67
+ for (const prop of key) if (!isReference(prop)) fields.add(prop);
68
+ if (options.version) fields.add(options.version);
69
+ if (options.generated) fields.add(options.generated);
70
+ return {
71
+ type,
72
+ name: type.name,
73
+ key,
74
+ fields: [...fields],
75
+ references,
76
+ children: (options.children ?? []).map((c): ChildrenModel => ({
77
+ prop: c.prop,
78
+ target: c.target,
79
+ parentRef: c.parentRef,
80
+ orderBy: c.orderBy,
81
+ })),
82
+ version: options.version,
83
+ generated: options.generated,
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Check the mappings fit together, so a mistake fails when the app is built rather than at the
89
+ * first query: every key, reference and child names something mapped.
90
+ */
91
+ function check(entities: readonly MemoryEntity[]): Map<EntityClass, MemoryEntity> {
92
+ const byType = new Map<EntityClass, MemoryEntity>();
93
+ for (const entity of entities) {
94
+ if (byType.has(entity.type)) {
95
+ throw new DataConfigurationError(`${entity.name} is mapped twice`);
96
+ }
97
+ byType.set(entity.type, entity);
98
+ }
99
+ const mapped = (owner: MemoryEntity, prop: string, target: EntityClass) => {
100
+ const found = byType.get(target);
101
+ if (found == null) {
102
+ throw new DataConfigurationError(
103
+ `${owner.name}.${prop} points at ${target.name}, which isn't mapped: add it to entities`,
104
+ );
105
+ }
106
+ return found;
107
+ };
108
+ for (const entity of entities) {
109
+ const { name } = entity;
110
+ const isReference = (prop: string) => entity.references.some((r) => r.prop === prop);
111
+ if (entity.key.length === 0) {
112
+ throw new DataConfigurationError(`${name} has no key`);
113
+ }
114
+ if (entity.generated && (entity.key.length !== 1 || entity.key[0] !== entity.generated)) {
115
+ throw new DataConfigurationError(
116
+ `${name}.${entity.generated} is generated, so it must be the whole key`,
117
+ );
118
+ }
119
+ for (const ref of entity.references) {
120
+ if (entity.fields.includes(ref.prop)) {
121
+ throw new DataConfigurationError(
122
+ `${name}.${ref.prop} is both a field and a reference`,
123
+ );
124
+ }
125
+ const target = mapped(entity, ref.prop, ref.target);
126
+ if (target.key.length !== 1) {
127
+ throw new DataConfigurationError(
128
+ `${name}.${ref.prop} references ${target.name}, whose key is composite: a reference must point at a single key`,
129
+ );
130
+ }
131
+ }
132
+ for (const spec of entity.children) {
133
+ const child = mapped(entity, spec.prop, spec.target);
134
+ const parentRef = child.references.find((r) => r.prop === spec.parentRef);
135
+ if (parentRef == null || parentRef.target !== entity.type) {
136
+ throw new DataConfigurationError(
137
+ `${name}.${spec.prop}: ${child.name}.${spec.parentRef} must be a reference to ${name}`,
138
+ );
139
+ }
140
+ }
141
+ for (const prop of entity.key) {
142
+ if (!entity.fields.includes(prop) && !isReference(prop)) {
143
+ throw new DataConfigurationError(`${name}'s key ${prop} isn't mapped`);
144
+ }
145
+ }
146
+ }
147
+ return byType;
148
+ }
149
+
150
+ export const memoryEntities = { check };
@@ -0,0 +1,63 @@
1
+ import type { BuilderPlugin } from "@decohere/core/hosting";
2
+ import type { Constructable } from "@decohere/core/reflection";
3
+ import {
4
+ DataConfigurationError,
5
+ DEFAULT_DATA_SOURCE,
6
+ type IUnitOfWork,
7
+ type OutboxMapper,
8
+ TrackingUnitOfWork,
9
+ } from "@decohere/data";
10
+ import type { MemoryEntity } from "./memory-entity.js";
11
+ import { MemoryRowStore } from "./memory.row-store.js";
12
+ import { MemoryStore } from "./memory.store.js";
13
+
14
+ export type MemoryModuleConfig = {
15
+ /** The data source's name, as `@injectUnitOfWork(name)` asks for it. Required when there are several. */
16
+ name?: string;
17
+ /** Each mapped class: `mapEntity(Order, { … })`. */
18
+ entities: MemoryEntity[];
19
+ repositories?: Constructable[];
20
+ /** Writes the events aggregates raise to an outbox entity, in the same commit. */
21
+ outbox?: OutboxMapper;
22
+ /** Runs when the app starts, with a unit of work that is committed when it returns. */
23
+ seed?: (unitOfWork: IUnitOfWork) => Promise<void>;
24
+ };
25
+
26
+ /**
27
+ * Keep the data in the process, with no database: for tests and local runs. Each build of the app
28
+ * gets empty stores of its own. Needs no `database` config.
29
+ */
30
+ export function memory(config: MemoryModuleConfig[] | MemoryModuleConfig): BuilderPlugin {
31
+ const modules = Array.isArray(config) ? config : [config];
32
+ if (modules.length > 1 && modules.some((m) => m.name == null)) {
33
+ throw new DataConfigurationError("Name is required if there is more than one datasource");
34
+ }
35
+ return (builder) => {
36
+ const stores = new Map<MemoryModuleConfig, MemoryStore>();
37
+ builder.withServices((containerBuilder) => {
38
+ for (const module of modules) {
39
+ const store = new MemoryStore(module.entities);
40
+ stores.set(module, store);
41
+ containerBuilder.registerRequestScoped(
42
+ module.name ?? DEFAULT_DATA_SOURCE,
43
+ () => new TrackingUnitOfWork(new MemoryRowStore(store), { outbox: module.outbox }),
44
+ );
45
+ for (const repository of module.repositories ?? []) {
46
+ containerBuilder.registerRequestScoped(repository);
47
+ }
48
+ }
49
+ });
50
+ if (modules.every((m) => m.seed == null)) return;
51
+ builder.registerStartStep(async () => {
52
+ for (const module of modules) {
53
+ const store = stores.get(module);
54
+ if (module.seed == null || store == null) continue;
55
+ await using unitOfWork = new TrackingUnitOfWork(new MemoryRowStore(store), {
56
+ outbox: module.outbox,
57
+ });
58
+ await module.seed(unitOfWork);
59
+ await unitOfWork.commit();
60
+ }
61
+ }, "memory data sources");
62
+ };
63
+ }
@@ -0,0 +1,87 @@
1
+ import {
2
+ DataError,
3
+ type EntityClass,
4
+ type EntityModel,
5
+ type Row,
6
+ type RowQuery,
7
+ type RowStore,
8
+ } from "@decohere/data";
9
+ import type { MemoryStore, MemoryTransaction } from "./memory.store.js";
10
+
11
+ /**
12
+ * The memory provider's share of the unit of work: one transaction at a time on a
13
+ * {@link MemoryStore}. Outside a transaction each operation runs in one of its own, as a database
14
+ * runs a statement on its own.
15
+ */
16
+ export class MemoryRowStore implements RowStore {
17
+ private transaction: MemoryTransaction | undefined;
18
+
19
+ public constructor(private readonly store: MemoryStore) {}
20
+
21
+ public model(type: EntityClass): EntityModel {
22
+ return this.store.model(type);
23
+ }
24
+
25
+ public async begin() {
26
+ if (this.transaction) throw new DataError("A transaction is already open");
27
+ this.transaction = this.store.begin();
28
+ }
29
+
30
+ public async commit() {
31
+ this.store.commit(this.end());
32
+ }
33
+
34
+ public async rollback() {
35
+ this.store.rollback(this.end());
36
+ }
37
+
38
+ public async release() {
39
+ if (this.transaction) await this.rollback();
40
+ }
41
+
42
+ public inTransaction() {
43
+ return this.transaction != null;
44
+ }
45
+
46
+ public select(type: EntityClass, query: RowQuery): Promise<Row[]> {
47
+ return this.run((tx) => this.store.select(tx, type, query));
48
+ }
49
+
50
+ public insert(type: EntityClass, rows: Row[]): Promise<Row[]> {
51
+ return this.run((tx) => this.store.insert(tx, type, rows));
52
+ }
53
+
54
+ public update(
55
+ type: EntityClass,
56
+ key: Row,
57
+ changes: Row,
58
+ version?: { prop: string; expected: unknown },
59
+ ): Promise<number> {
60
+ return this.run((tx) => this.store.update(tx, type, key, changes, version));
61
+ }
62
+
63
+ public delete(type: EntityClass, keys: Row[]): Promise<void> {
64
+ return this.run((tx) => this.store.delete(tx, type, keys));
65
+ }
66
+
67
+ private end(): MemoryTransaction {
68
+ const tx = this.transaction;
69
+ if (tx == null) throw new DataError("No transaction is open");
70
+ this.transaction = undefined;
71
+ return tx;
72
+ }
73
+
74
+ private async run<R>(operation: (tx: MemoryTransaction) => Promise<R>): Promise<R> {
75
+ if (this.transaction) return operation(this.transaction);
76
+ const tx = this.store.begin();
77
+ let result: R;
78
+ try {
79
+ result = await operation(tx);
80
+ } catch (err) {
81
+ this.store.rollback(tx);
82
+ throw err;
83
+ }
84
+ this.store.commit(tx);
85
+ return result;
86
+ }
87
+ }