@entifix/mongo 0.23.14 → 0.23.15
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.
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { EntityRepository } from '@entifix/business';
|
|
2
|
-
import { Entity, EntityConstructor } from '@entifix/core';
|
|
2
|
+
import { Entity, EntityConstructor, type UniqueMember } from '@entifix/core';
|
|
3
3
|
import type { ClientSession, Db } from 'mongodb';
|
|
4
4
|
/** The collection an entity's records live in: its `key`, else its class name. */
|
|
5
5
|
export declare function mongoCollectionName<TEntity extends Entity>(entityConstructor: EntityConstructor<TEntity>): string;
|
|
6
|
+
/** The index a unique member is held to: named for the member, partial. */
|
|
7
|
+
export declare const uniqueIndexName: (member: UniqueMember) => string;
|
|
6
8
|
/**
|
|
7
9
|
* Builds an {@link EntityRepository} for a single entity type, backed by a live
|
|
8
10
|
* mongodb {@link Db}. The `db` and `entityConstructor` are captured in closures,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make-mongo-repository.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAsB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAIL,MAAM,EACN,iBAAiB,
|
|
1
|
+
{"version":3,"file":"make-mongo-repository.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAsB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAIL,MAAM,EACN,iBAAiB,EAejB,KAAK,YAAY,EAElB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAajD,kFAAkF;AAClF,wBAAgB,mBAAmB,CAAC,OAAO,SAAS,MAAM,EACxD,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,GAC5C,MAAM,CAGR;AAaD,2EAA2E;AAC3E,eAAO,MAAM,eAAe,GAAI,QAAQ,YAAY,KAAG,MAC/B,CAAC;AAsCzB;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,SAAS,MAAM,EACxD,EAAE,EAAE,EAAE,EACN,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAC7C,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,OAAO,CAAC,EAAE,aAAa,CAAA;CAAE,GAC7C,gBAAgB,CAmSlB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, holdsStoredState, NotFound, readRevision, relevanceLabelKey, relevanceTerms, serializeEntity, StaleRevision, storedStateCondition, unavailableInState } from '@entifix/core';
|
|
3
|
+
import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, holdsStoredState, NotFound, readRevision, relevanceLabelKey, relevanceTerms, serializeEntity, StaleRevision, storedStateCondition, unavailableInState, uniqueMembersOf } from '@entifix/core';
|
|
4
4
|
import { Effect } from 'effect';
|
|
5
5
|
import { translateMongoError } from '../errors/translate-mongo-error.js';
|
|
6
6
|
import { RELEVANCE_FIELD, relevanceExpression, translateFiltering, translateSorting } from './filter-translator.js';
|
|
@@ -15,23 +15,44 @@ import { RELEVANCE_FIELD, relevanceExpression, translateFiltering, translateSort
|
|
|
15
15
|
return (_metaEntity_key = metaEntity.key) != null ? _metaEntity_key : metaEntity.name;
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* The collections whose unique
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
18
|
+
* The collections whose unique indexes are known to exist, per database: the
|
|
19
|
+
* one on `id`, and one per member the entity declares `unique` (ADR 0034).
|
|
20
|
+
*
|
|
21
|
+
* A create is atomic only against an index: two concurrent creates of one
|
|
22
|
+
* client-minted id — or of one vendor's code — would otherwise both insert.
|
|
23
|
+
* Keyed on the `Db` so a fake or a reset database starts clean, and a rejected
|
|
24
|
+
* attempt is forgotten so the next write tries again.
|
|
25
|
+
*/ const ensuredIndexes = new WeakMap();
|
|
26
|
+
/** The index a unique member is held to: named for the member, partial. */ export const uniqueIndexName = (member)=>`unique_${member.key}`;
|
|
27
|
+
const ensureIndexes = (db, name, uniques)=>Effect.suspend(()=>{
|
|
28
|
+
var _ensuredIndexes_get;
|
|
29
|
+
const ensured = (_ensuredIndexes_get = ensuredIndexes.get(db)) != null ? _ensuredIndexes_get : new Set();
|
|
30
|
+
ensuredIndexes.set(db, ensured);
|
|
28
31
|
if (ensured.has(name)) return Effect.void;
|
|
32
|
+
const collection = db.collection(name);
|
|
29
33
|
return Effect.tryPromise({
|
|
30
|
-
try: ()=>
|
|
34
|
+
try: async ()=>{
|
|
35
|
+
await collection.createIndex({
|
|
31
36
|
id: 1
|
|
32
37
|
}, {
|
|
33
38
|
unique: true
|
|
34
|
-
})
|
|
39
|
+
});
|
|
40
|
+
// Partial over the documents that hold a value of the member's type,
|
|
41
|
+
// so an optional member left empty never collides with another.
|
|
42
|
+
for (const member of uniques){
|
|
43
|
+
await collection.createIndex({
|
|
44
|
+
[member.key]: 1
|
|
45
|
+
}, {
|
|
46
|
+
unique: true,
|
|
47
|
+
name: uniqueIndexName(member),
|
|
48
|
+
partialFilterExpression: {
|
|
49
|
+
[member.key]: {
|
|
50
|
+
$type: member.type
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
},
|
|
35
56
|
catch: (error)=>translateMongoError(error)
|
|
36
57
|
}).pipe(Effect.tap(()=>Effect.sync(()=>ensured.add(name))));
|
|
37
58
|
});
|
|
@@ -58,6 +79,10 @@ function toEntityId(entityOrId) {
|
|
|
58
79
|
*/ export function makeMongoRepository(db, entityConstructor, options) {
|
|
59
80
|
const collectionName = mongoCollectionName(entityConstructor);
|
|
60
81
|
const collection = db.collection(collectionName);
|
|
82
|
+
const uniques = uniqueMembersOf(entityConstructor);
|
|
83
|
+
// Every write is held to the unique members' indexes, not only a create: an
|
|
84
|
+
// update onto another record's value collides exactly as a create does.
|
|
85
|
+
const indexed = uniques.length === 0 ? Effect.void : ensureIndexes(db, collectionName, uniques);
|
|
61
86
|
// Spread into every call, so a repository with no session passes none.
|
|
62
87
|
const inSession = (options == null ? void 0 : options.session) ? {
|
|
63
88
|
session: options.session
|
|
@@ -159,14 +184,16 @@ function toEntityId(entityOrId) {
|
|
|
159
184
|
const read = readRevision(entity);
|
|
160
185
|
const id = (_entity_id = entity.id) != null ? _entity_id : randomUUID();
|
|
161
186
|
if (read === undefined) {
|
|
162
|
-
yield*
|
|
187
|
+
yield* ensureIndexes(db, collectionName, uniques);
|
|
163
188
|
yield* Effect.tryPromise({
|
|
164
189
|
try: ()=>collection.insertOne(_extends({}, doc, {
|
|
165
190
|
id,
|
|
166
191
|
revision: 1
|
|
167
192
|
}), inSession),
|
|
168
193
|
catch: (error)=>translateMongoError(error)
|
|
169
|
-
}).pipe(
|
|
194
|
+
}).pipe(// Only the identity's index means "someone created it first"; a
|
|
195
|
+
// unique member's names the member, which a form shows on the field.
|
|
196
|
+
Effect.mapError((failure)=>failure._tag === 'DuplicateKey' && failure.key === 'id' ? new StaleRevision({
|
|
170
197
|
entity: key
|
|
171
198
|
}) : failure));
|
|
172
199
|
entity.id = id;
|
|
@@ -205,8 +232,8 @@ function toEntityId(entityOrId) {
|
|
|
205
232
|
});
|
|
206
233
|
const save = (entity, options)=>{
|
|
207
234
|
const condition = conditionOf(options);
|
|
208
|
-
|
|
209
|
-
return
|
|
235
|
+
const write = revised ? saveRevised(entity, condition) : condition === undefined ? saveUnchecked(entity) : saveConditioned(entity, condition);
|
|
236
|
+
return Effect.andThen(indexed, write);
|
|
210
237
|
};
|
|
211
238
|
/**
|
|
212
239
|
* An update of a record that declares no revision, on the states it must
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/make-mongo-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository, EntityWriteOptions } from '@entifix/business';\nimport {\n declaresRevision,\n deserializeEntityCollection,\n deserializeSingleEntity,\n Entity,\n EntityConstructor,\n EntityId,\n EntityLoadRequest,\n EntityPage,\n extractMetaEntity,\n holdsStoredState,\n NotFound,\n readRevision,\n relevanceLabelKey,\n relevanceTerms,\n serializeEntity,\n StaleRevision,\n type StoredStateCondition,\n storedStateCondition,\n unavailableInState,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport {\n RELEVANCE_FIELD,\n relevanceExpression,\n translateFiltering,\n translateSorting,\n} from './filter-translator.js';\n\n/** Projection that drops Mongo's internal `_id` from read results. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** The collection an entity's records live in: its `key`, else its class name. */\nexport function mongoCollectionName<TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n): string {\n const metaEntity = extractMetaEntity(entityConstructor);\n return metaEntity.key ?? metaEntity.name;\n}\n\n/**\n * The collections whose unique index on `id` is known to exist, per database.\n * A create is atomic only against that index: two concurrent creates of one\n * client-minted id would otherwise both insert. Keyed on the `Db` so a fake or\n * a reset database starts clean, and a rejected attempt is forgotten so the\n * next create tries again.\n */\nconst ensuredIdIndexes = new WeakMap<Db, Set<string>>();\n\nconst ensureIdIndex = (db: Db, name: string) =>\n Effect.suspend(() => {\n const ensured = ensuredIdIndexes.get(db) ?? new Set<string>();\n ensuredIdIndexes.set(db, ensured);\n if (ensured.has(name)) return Effect.void;\n return Effect.tryPromise({\n try: () => db.collection(name).createIndex({ id: 1 }, { unique: true }),\n catch: error => translateMongoError(error),\n }).pipe(Effect.tap(() => Effect.sync(() => ensured.add(name))));\n });\n\nfunction toEntityId(entityOrId: EntityId | Entity): EntityId {\n return entityOrId != null && typeof entityOrId === 'object'\n ? (entityOrId as Entity).id\n : (entityOrId as EntityId);\n}\n\n/**\n * Builds an {@link EntityRepository} for a single entity type, backed by a live\n * mongodb {@link Db}. The `db` and `entityConstructor` are captured in closures,\n * so every method's Effect has no outstanding requirements (`R = never`), which\n * is exactly what the interface asks.\n *\n * Collection name = the entity's `key` (falling back to its class name). Reads\n * reuse the shared entifix deserializer (rebuilding links from embedded objects\n * or scalar FKs); writes reuse the shared serializer. Mongo failures surface as\n * categorised failures — `NotFound`, `DuplicateKey`, `Unavailable` and the\n * rest — through `translateMongoError`.\n *\n * This is the Mongo mirror of the REST `buildEntityRestAdapter*` builders.\n *\n * Pass `session` to make the repository part of a transaction — a unit of\n * work's handle — so its writes commit with the unit and its reads see what the\n * unit has already written.\n */\nexport function makeMongoRepository<TEntity extends Entity>(\n db: Db,\n entityConstructor: EntityConstructor<TEntity>,\n options?: { readonly session?: ClientSession },\n): EntityRepository {\n const collectionName = mongoCollectionName(entityConstructor);\n const collection = db.collection(collectionName);\n // Spread into every call, so a repository with no session passes none.\n const inSession = options?.session ? { session: options.session } : {};\n\n const load = <T extends Entity>(request: EntityLoadRequest<T>) =>\n Effect.gen(function* () {\n const filter = translateFiltering(request.filtering);\n const sort = translateSorting(request.sorting);\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const skip = (page - 1) * pageSize;\n\n // A relevance order is a field computed from the request's own words,\n // which a `find` cannot sort by: the same page through a pipeline\n // (ADR 0033).\n const docs = yield* Effect.tryPromise({\n try: () =>\n RELEVANCE_FIELD in sort\n ? collection\n .aggregate(\n [\n { $match: filter },\n {\n $addFields: {\n [RELEVANCE_FIELD]: relevanceExpression(\n relevanceLabelKey(entityConstructor),\n relevanceTerms(request.filtering),\n ),\n },\n },\n { $sort: sort },\n { $skip: skip },\n { $limit: pageSize },\n { $project: { _id: 0, [RELEVANCE_FIELD]: 0 } },\n ],\n inSession,\n )\n .toArray()\n : collection\n .find(filter, { ...WITHOUT_MONGO_ID, ...inSession })\n .sort(sort)\n .skip(skip)\n .limit(pageSize)\n .toArray(),\n catch: error => translateMongoError(error),\n });\n const total = yield* Effect.tryPromise({\n try: () => collection.countDocuments(filter, inSession),\n catch: error => translateMongoError(error),\n });\n\n const items = yield* deserializeEntityCollection(entityConstructor, docs);\n\n return {\n items: items as unknown as T[],\n total,\n request,\n } satisfies EntityPage<T>;\n });\n\n const get = <T extends Entity>(id: EntityId) =>\n Effect.gen(function* () {\n const doc = yield* Effect.tryPromise({\n try: () =>\n collection.findOne({ id }, { ...WITHOUT_MONGO_ID, ...inSession }),\n catch: error => translateMongoError(error),\n });\n const entity = yield* deserializeSingleEntity(entityConstructor, doc);\n if (entity === undefined) {\n return yield* Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n }\n return entity as unknown as T;\n });\n\n const revised = declaresRevision(entityConstructor);\n\n /** The `expect` of a write, resolved to the field the store holds it under. */\n const conditionOf = (\n options: EntityWriteOptions | undefined,\n ): StoredStateCondition | undefined =>\n options?.expect === undefined\n ? undefined\n : storedStateCondition(entityConstructor, options.expect);\n\n /** The filter clause a condition adds to a write. */\n const stateFilter = (condition: StoredStateCondition | undefined) =>\n condition === undefined\n ? {}\n : { [condition.key]: { $in: [...condition.in] } };\n\n /** What a write that matched nothing reads back, only to name the refusal. */\n const readBack = (id: EntityId, condition?: StoredStateCondition) =>\n Effect.tryPromise({\n try: () =>\n collection.findOne(\n { id },\n {\n projection: {\n _id: 0,\n revision: 1,\n ...(condition === undefined ? {} : { [condition.key]: 1 }),\n },\n ...inSession,\n },\n ),\n catch: error => translateMongoError(error),\n });\n\n /**\n * A save of an entity that declares a revision (ADR 0032): a create that\n * never overwrites, or one conditional write on the revision the caller read.\n * Never a read followed by a write — two saves would both read `n`.\n */\n const saveRevised = <T extends Entity>(\n entity: T,\n condition: StoredStateCondition | undefined,\n ) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const read = readRevision(entity);\n const id = entity.id ?? randomUUID();\n if (read === undefined) {\n yield* ensureIdIndex(db, collectionName);\n yield* Effect.tryPromise({\n try: () =>\n collection.insertOne({ ...doc, id, revision: 1 }, inSession),\n catch: error => translateMongoError(error),\n }).pipe(\n Effect.mapError(failure =>\n failure._tag === 'DuplicateKey'\n ? new StaleRevision({ entity: key })\n : failure,\n ),\n );\n entity.id = id;\n (entity as { revision?: number }).revision = 1;\n return entity;\n }\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, revision: read, ...stateFilter(condition) },\n { ...doc, id, revision: read + 1 },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n // The write already decided; this read only names the refusal. A\n // record in another state is refused for its state before its\n // revision: a fresher read would not make the save legal.\n const stored = yield* readBack(id, condition);\n if (stored === null) return yield* new NotFound({ entity: key });\n if (condition !== undefined && !holdsStoredState(condition, stored)) {\n return yield* unavailableInState(\n entityConstructor,\n condition,\n stored,\n );\n }\n return yield* Effect.fail(\n new StaleRevision({\n entity: key,\n current: readRevision(stored),\n }),\n );\n }\n entity.id = id;\n (entity as { revision?: number }).revision = read + 1;\n return entity;\n });\n\n const save = <T extends Entity>(entity: T, options?: EntityWriteOptions) => {\n const condition = conditionOf(options);\n if (revised) return saveRevised(entity, condition);\n return condition === undefined\n ? saveUnchecked(entity)\n : saveConditioned(entity, condition);\n };\n\n /**\n * An update of a record that declares no revision, on the states it must\n * hold: one `replaceOne` on the id and the state, never an upsert — a save\n * with `expect` is an update of a stored record.\n */\n const saveConditioned = <T extends Entity>(\n entity: T,\n condition: StoredStateCondition,\n ) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const id = entity.id;\n if (id === undefined) return yield* new NotFound({ entity: key });\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, ...stateFilter(condition) },\n { ...doc, id },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n const stored = yield* readBack(id, condition);\n return yield* stored === null\n ? Effect.fail(new NotFound({ entity: key }))\n : Effect.fail(\n unavailableInState(entityConstructor, condition, stored),\n );\n }\n return entity;\n });\n\n const saveUnchecked = <T extends Entity>(entity: T) =>\n Effect.gen(function* () {\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n // A create arrives without an id, so the store mints one. Entities are\n // addressed by their own `id` field (never Mongo's `_id`, which reads\n // project away), so an inserted document without one would be\n // unreachable by `get` and by any later `replaceOne`.\n const id = entity.id ?? randomUUID();\n yield* Effect.tryPromise({\n // `doc` omits `id` when it was undefined (the serializer drops\n // undefined), hence spreading the resolved id back in.\n try: () =>\n collection.replaceOne(\n { id },\n { ...doc, id },\n { upsert: true, ...inSession },\n ),\n catch: error => translateMongoError(error),\n });\n entity.id = id;\n return entity;\n });\n\n const del = <T extends Entity>(\n entityOrId: EntityId | T,\n options?: EntityWriteOptions,\n ) =>\n Effect.gen(function* () {\n const id = toEntityId(entityOrId);\n const condition = conditionOf(options);\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.deleteOne({ id, ...stateFilter(condition) }, inSession),\n catch: error => translateMongoError(error),\n });\n if (condition === undefined || result.deletedCount > 0) return;\n // Nothing deleted: either nothing was there, which a delete accepts,\n // or the record is in a state it may not be deleted from.\n const stored = yield* readBack(id, condition);\n if (stored !== null) {\n return yield* unavailableInState(entityConstructor, condition, stored);\n }\n });\n\n // Cast through the interface to keep its generic signatures: each method here\n // is written against this entity's type, the interface against any entity's.\n return {\n load,\n get,\n save,\n delete: del,\n } as unknown as EntityRepository;\n}\n"],"names":["randomUUID","declaresRevision","deserializeEntityCollection","deserializeSingleEntity","extractMetaEntity","holdsStoredState","NotFound","readRevision","relevanceLabelKey","relevanceTerms","serializeEntity","StaleRevision","storedStateCondition","unavailableInState","Effect","translateMongoError","RELEVANCE_FIELD","relevanceExpression","translateFiltering","translateSorting","WITHOUT_MONGO_ID","projection","_id","mongoCollectionName","entityConstructor","metaEntity","key","name","ensuredIdIndexes","WeakMap","ensureIdIndex","db","suspend","ensured","get","Set","set","has","void","tryPromise","try","collection","createIndex","id","unique","catch","error","pipe","tap","sync","add","toEntityId","entityOrId","makeMongoRepository","options","collectionName","inSession","session","load","request","gen","filter","filtering","sort","sorting","page","pageSize","skip","docs","aggregate","$match","$addFields","$sort","$skip","$limit","$project","toArray","find","limit","total","countDocuments","items","doc","findOne","entity","undefined","fail","revised","conditionOf","expect","stateFilter","condition","$in","in","readBack","revision","saveRevised","read","insertOne","mapError","failure","_tag","result","replaceOne","matchedCount","stored","current","save","saveUnchecked","saveConditioned","upsert","del","deleteOne","deletedCount","delete"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,gBAAgB,EAChBC,2BAA2B,EAC3BC,uBAAuB,EAMvBC,iBAAiB,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACZC,iBAAiB,EACjBC,cAAc,EACdC,eAAe,EACfC,aAAa,EAEbC,oBAAoB,EACpBC,kBAAkB,QACb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SACEC,eAAe,EACfC,mBAAmB,EACnBC,kBAAkB,EAClBC,gBAAgB,QACX,yBAAyB;AAEhC,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAarB,kBAAkBoB;IACrC,QAAOC,kBAAAA,WAAWC,GAAG,YAAdD,kB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AAS/B,oBAAoB+B;YACtC;YACAsC,OAAOzC,EAAE,GAAGA;YACZ,OAAOyC;QACT;IAEF,MAAM2B,MAAM,CACV3D,YACAE,UAEAxC,OAAO8C,GAAG,CAAC;YACT,MAAMjB,KAAKQ,WAAWC;YACtB,MAAMuC,YAAYH,YAAYlC;YAC9B,MAAMgD,SAAS,OAAOxF,OAAOyB,UAAU,CAAC;gBACtCC,KAAK,IACHC,WAAWuE,SAAS,CAAC;wBAAErE;uBAAO+C,YAAYC,aAAcnC;gBAC1DX,OAAOC,CAAAA,QAAS/B,oBAAoB+B;YACtC;YACA,IAAI6C,cAAcN,aAAaiB,OAAOW,YAAY,GAAG,GAAG;YACxD,qEAAqE;YACrE,0DAA0D;YAC1D,MAAMR,SAAS,OAAOX,SAASnD,IAAIgD;YACnC,IAAIc,WAAW,MAAM;gBACnB,OAAO,OAAO5F,mBAAmBW,mBAAmBmE,WAAWc;YACjE;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACL/C;QACAxB;QACAyE;QACAO,QAAQH;IACV;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/make-mongo-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository, EntityWriteOptions } from '@entifix/business';\nimport {\n declaresRevision,\n deserializeEntityCollection,\n deserializeSingleEntity,\n Entity,\n EntityConstructor,\n EntityId,\n EntityLoadRequest,\n EntityPage,\n extractMetaEntity,\n holdsStoredState,\n NotFound,\n readRevision,\n relevanceLabelKey,\n relevanceTerms,\n serializeEntity,\n StaleRevision,\n type StoredStateCondition,\n storedStateCondition,\n unavailableInState,\n type UniqueMember,\n uniqueMembersOf,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport {\n RELEVANCE_FIELD,\n relevanceExpression,\n translateFiltering,\n translateSorting,\n} from './filter-translator.js';\n\n/** Projection that drops Mongo's internal `_id` from read results. */\nconst WITHOUT_MONGO_ID = { projection: { _id: 0 } } as const;\n\n/** The collection an entity's records live in: its `key`, else its class name. */\nexport function mongoCollectionName<TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n): string {\n const metaEntity = extractMetaEntity(entityConstructor);\n return metaEntity.key ?? metaEntity.name;\n}\n\n/**\n * The collections whose unique indexes are known to exist, per database: the\n * one on `id`, and one per member the entity declares `unique` (ADR 0034).\n *\n * A create is atomic only against an index: two concurrent creates of one\n * client-minted id — or of one vendor's code — would otherwise both insert.\n * Keyed on the `Db` so a fake or a reset database starts clean, and a rejected\n * attempt is forgotten so the next write tries again.\n */\nconst ensuredIndexes = new WeakMap<Db, Set<string>>();\n\n/** The index a unique member is held to: named for the member, partial. */\nexport const uniqueIndexName = (member: UniqueMember): string =>\n `unique_${member.key}`;\n\nconst ensureIndexes = (\n db: Db,\n name: string,\n uniques: readonly UniqueMember[],\n) =>\n Effect.suspend(() => {\n const ensured = ensuredIndexes.get(db) ?? new Set<string>();\n ensuredIndexes.set(db, ensured);\n if (ensured.has(name)) return Effect.void;\n const collection = db.collection(name);\n return Effect.tryPromise({\n try: async () => {\n await collection.createIndex({ id: 1 }, { unique: true });\n // Partial over the documents that hold a value of the member's type,\n // so an optional member left empty never collides with another.\n for (const member of uniques) {\n await collection.createIndex(\n { [member.key]: 1 },\n {\n unique: true,\n name: uniqueIndexName(member),\n partialFilterExpression: { [member.key]: { $type: member.type } },\n },\n );\n }\n },\n catch: error => translateMongoError(error),\n }).pipe(Effect.tap(() => Effect.sync(() => ensured.add(name))));\n });\n\nfunction toEntityId(entityOrId: EntityId | Entity): EntityId {\n return entityOrId != null && typeof entityOrId === 'object'\n ? (entityOrId as Entity).id\n : (entityOrId as EntityId);\n}\n\n/**\n * Builds an {@link EntityRepository} for a single entity type, backed by a live\n * mongodb {@link Db}. The `db` and `entityConstructor` are captured in closures,\n * so every method's Effect has no outstanding requirements (`R = never`), which\n * is exactly what the interface asks.\n *\n * Collection name = the entity's `key` (falling back to its class name). Reads\n * reuse the shared entifix deserializer (rebuilding links from embedded objects\n * or scalar FKs); writes reuse the shared serializer. Mongo failures surface as\n * categorised failures — `NotFound`, `DuplicateKey`, `Unavailable` and the\n * rest — through `translateMongoError`.\n *\n * This is the Mongo mirror of the REST `buildEntityRestAdapter*` builders.\n *\n * Pass `session` to make the repository part of a transaction — a unit of\n * work's handle — so its writes commit with the unit and its reads see what the\n * unit has already written.\n */\nexport function makeMongoRepository<TEntity extends Entity>(\n db: Db,\n entityConstructor: EntityConstructor<TEntity>,\n options?: { readonly session?: ClientSession },\n): EntityRepository {\n const collectionName = mongoCollectionName(entityConstructor);\n const collection = db.collection(collectionName);\n const uniques = uniqueMembersOf(entityConstructor);\n // Every write is held to the unique members' indexes, not only a create: an\n // update onto another record's value collides exactly as a create does.\n const indexed =\n uniques.length === 0\n ? Effect.void\n : ensureIndexes(db, collectionName, uniques);\n // Spread into every call, so a repository with no session passes none.\n const inSession = options?.session ? { session: options.session } : {};\n\n const load = <T extends Entity>(request: EntityLoadRequest<T>) =>\n Effect.gen(function* () {\n const filter = translateFiltering(request.filtering);\n const sort = translateSorting(request.sorting);\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const skip = (page - 1) * pageSize;\n\n // A relevance order is a field computed from the request's own words,\n // which a `find` cannot sort by: the same page through a pipeline\n // (ADR 0033).\n const docs = yield* Effect.tryPromise({\n try: () =>\n RELEVANCE_FIELD in sort\n ? collection\n .aggregate(\n [\n { $match: filter },\n {\n $addFields: {\n [RELEVANCE_FIELD]: relevanceExpression(\n relevanceLabelKey(entityConstructor),\n relevanceTerms(request.filtering),\n ),\n },\n },\n { $sort: sort },\n { $skip: skip },\n { $limit: pageSize },\n { $project: { _id: 0, [RELEVANCE_FIELD]: 0 } },\n ],\n inSession,\n )\n .toArray()\n : collection\n .find(filter, { ...WITHOUT_MONGO_ID, ...inSession })\n .sort(sort)\n .skip(skip)\n .limit(pageSize)\n .toArray(),\n catch: error => translateMongoError(error),\n });\n const total = yield* Effect.tryPromise({\n try: () => collection.countDocuments(filter, inSession),\n catch: error => translateMongoError(error),\n });\n\n const items = yield* deserializeEntityCollection(entityConstructor, docs);\n\n return {\n items: items as unknown as T[],\n total,\n request,\n } satisfies EntityPage<T>;\n });\n\n const get = <T extends Entity>(id: EntityId) =>\n Effect.gen(function* () {\n const doc = yield* Effect.tryPromise({\n try: () =>\n collection.findOne({ id }, { ...WITHOUT_MONGO_ID, ...inSession }),\n catch: error => translateMongoError(error),\n });\n const entity = yield* deserializeSingleEntity(entityConstructor, doc);\n if (entity === undefined) {\n return yield* Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n }\n return entity as unknown as T;\n });\n\n const revised = declaresRevision(entityConstructor);\n\n /** The `expect` of a write, resolved to the field the store holds it under. */\n const conditionOf = (\n options: EntityWriteOptions | undefined,\n ): StoredStateCondition | undefined =>\n options?.expect === undefined\n ? undefined\n : storedStateCondition(entityConstructor, options.expect);\n\n /** The filter clause a condition adds to a write. */\n const stateFilter = (condition: StoredStateCondition | undefined) =>\n condition === undefined\n ? {}\n : { [condition.key]: { $in: [...condition.in] } };\n\n /** What a write that matched nothing reads back, only to name the refusal. */\n const readBack = (id: EntityId, condition?: StoredStateCondition) =>\n Effect.tryPromise({\n try: () =>\n collection.findOne(\n { id },\n {\n projection: {\n _id: 0,\n revision: 1,\n ...(condition === undefined ? {} : { [condition.key]: 1 }),\n },\n ...inSession,\n },\n ),\n catch: error => translateMongoError(error),\n });\n\n /**\n * A save of an entity that declares a revision (ADR 0032): a create that\n * never overwrites, or one conditional write on the revision the caller read.\n * Never a read followed by a write — two saves would both read `n`.\n */\n const saveRevised = <T extends Entity>(\n entity: T,\n condition: StoredStateCondition | undefined,\n ) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const read = readRevision(entity);\n const id = entity.id ?? randomUUID();\n if (read === undefined) {\n yield* ensureIndexes(db, collectionName, uniques);\n yield* Effect.tryPromise({\n try: () =>\n collection.insertOne({ ...doc, id, revision: 1 }, inSession),\n catch: error => translateMongoError(error),\n }).pipe(\n // Only the identity's index means \"someone created it first\"; a\n // unique member's names the member, which a form shows on the field.\n Effect.mapError(failure =>\n failure._tag === 'DuplicateKey' && failure.key === 'id'\n ? new StaleRevision({ entity: key })\n : failure,\n ),\n );\n entity.id = id;\n (entity as { revision?: number }).revision = 1;\n return entity;\n }\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, revision: read, ...stateFilter(condition) },\n { ...doc, id, revision: read + 1 },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n // The write already decided; this read only names the refusal. A\n // record in another state is refused for its state before its\n // revision: a fresher read would not make the save legal.\n const stored = yield* readBack(id, condition);\n if (stored === null) return yield* new NotFound({ entity: key });\n if (condition !== undefined && !holdsStoredState(condition, stored)) {\n return yield* unavailableInState(\n entityConstructor,\n condition,\n stored,\n );\n }\n return yield* Effect.fail(\n new StaleRevision({\n entity: key,\n current: readRevision(stored),\n }),\n );\n }\n entity.id = id;\n (entity as { revision?: number }).revision = read + 1;\n return entity;\n });\n\n const save = <T extends Entity>(entity: T, options?: EntityWriteOptions) => {\n const condition = conditionOf(options);\n const write = revised\n ? saveRevised(entity, condition)\n : condition === undefined\n ? saveUnchecked(entity)\n : saveConditioned(entity, condition);\n return Effect.andThen(indexed, write);\n };\n\n /**\n * An update of a record that declares no revision, on the states it must\n * hold: one `replaceOne` on the id and the state, never an upsert — a save\n * with `expect` is an update of a stored record.\n */\n const saveConditioned = <T extends Entity>(\n entity: T,\n condition: StoredStateCondition,\n ) =>\n Effect.gen(function* () {\n const key = extractMetaEntity(entityConstructor).key;\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n const id = entity.id;\n if (id === undefined) return yield* new NotFound({ entity: key });\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.replaceOne(\n { id, ...stateFilter(condition) },\n { ...doc, id },\n inSession,\n ),\n catch: error => translateMongoError(error),\n });\n if (result.matchedCount === 0) {\n const stored = yield* readBack(id, condition);\n return yield* stored === null\n ? Effect.fail(new NotFound({ entity: key }))\n : Effect.fail(\n unavailableInState(entityConstructor, condition, stored),\n );\n }\n return entity;\n });\n\n const saveUnchecked = <T extends Entity>(entity: T) =>\n Effect.gen(function* () {\n const doc = serializeEntity(\n entityConstructor,\n entity as unknown as TEntity,\n );\n // A create arrives without an id, so the store mints one. Entities are\n // addressed by their own `id` field (never Mongo's `_id`, which reads\n // project away), so an inserted document without one would be\n // unreachable by `get` and by any later `replaceOne`.\n const id = entity.id ?? randomUUID();\n yield* Effect.tryPromise({\n // `doc` omits `id` when it was undefined (the serializer drops\n // undefined), hence spreading the resolved id back in.\n try: () =>\n collection.replaceOne(\n { id },\n { ...doc, id },\n { upsert: true, ...inSession },\n ),\n catch: error => translateMongoError(error),\n });\n entity.id = id;\n return entity;\n });\n\n const del = <T extends Entity>(\n entityOrId: EntityId | T,\n options?: EntityWriteOptions,\n ) =>\n Effect.gen(function* () {\n const id = toEntityId(entityOrId);\n const condition = conditionOf(options);\n const result = yield* Effect.tryPromise({\n try: () =>\n collection.deleteOne({ id, ...stateFilter(condition) }, inSession),\n catch: error => translateMongoError(error),\n });\n if (condition === undefined || result.deletedCount > 0) return;\n // Nothing deleted: either nothing was there, which a delete accepts,\n // or the record is in a state it may not be deleted from.\n const stored = yield* readBack(id, condition);\n if (stored !== null) {\n return yield* unavailableInState(entityConstructor, condition, stored);\n }\n });\n\n // Cast through the interface to keep its generic signatures: each method here\n // is written against this entity's type, the interface against any entity's.\n return {\n load,\n get,\n save,\n delete: del,\n } as unknown as EntityRepository;\n}\n"],"names":["randomUUID","declaresRevision","deserializeEntityCollection","deserializeSingleEntity","extractMetaEntity","holdsStoredState","NotFound","readRevision","relevanceLabelKey","relevanceTerms","serializeEntity","StaleRevision","storedStateCondition","unavailableInState","uniqueMembersOf","Effect","translateMongoError","RELEVANCE_FIELD","relevanceExpression","translateFiltering","translateSorting","WITHOUT_MONGO_ID","projection","_id","mongoCollectionName","entityConstructor","metaEntity","key","name","ensuredIndexes","WeakMap","uniqueIndexName","member","ensureIndexes","db","uniques","suspend","ensured","get","Set","set","has","void","collection","tryPromise","try","createIndex","id","unique","partialFilterExpression","$type","type","catch","error","pipe","tap","sync","add","toEntityId","entityOrId","makeMongoRepository","options","collectionName","indexed","length","inSession","session","load","request","gen","filter","filtering","sort","sorting","page","pageSize","skip","docs","aggregate","$match","$addFields","$sort","$skip","$limit","$project","toArray","find","limit","total","countDocuments","items","doc","findOne","entity","undefined","fail","revised","conditionOf","expect","stateFilter","condition","$in","in","readBack","revision","saveRevised","read","insertOne","mapError","failure","_tag","result","replaceOne","matchedCount","stored","current","save","write","saveUnchecked","saveConditioned","andThen","upsert","del","deleteOne","deletedCount","delete"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,gBAAgB,EAChBC,2BAA2B,EAC3BC,uBAAuB,EAMvBC,iBAAiB,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACZC,iBAAiB,EACjBC,cAAc,EACdC,eAAe,EACfC,aAAa,EAEbC,oBAAoB,EACpBC,kBAAkB,EAElBC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SACEC,eAAe,EACfC,mBAAmB,EACnBC,kBAAkB,EAClBC,gBAAgB,QACX,yBAAyB;AAEhC,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAatB,kBAAkBqB;IACrC,QAAOC,kBAAAA,WAAWC,GAAG,YAAdD,kBAAkBA,WAAWE,IAAI;AAC1C;AAE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,mBAAmBY,mBAAmB2E,WAAWc;YACjE;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACL/C;QACA7B;QACA8E;QACAS,QAAQH;IACV;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/mongo",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.15",
|
|
4
4
|
"description": "MongoDB adapter: an entity repository, RSQL-to-Mongo query translation, per-tenant databases, and an optional transactional outbox.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -57,17 +57,17 @@
|
|
|
57
57
|
"dependencies": {
|
|
58
58
|
"@swc/helpers": "0.5.23",
|
|
59
59
|
"mongodb": "7.9.0",
|
|
60
|
-
"@entifix/
|
|
61
|
-
"@entifix/
|
|
60
|
+
"@entifix/business": "0.23.15",
|
|
61
|
+
"@entifix/core": "0.23.15"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
|
64
64
|
"effect": "4.0.7",
|
|
65
|
-
"@entifix/
|
|
66
|
-
"@entifix/
|
|
65
|
+
"@entifix/testing-unit": "0.23.15",
|
|
66
|
+
"@entifix/transactions": "0.23.15"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
69
|
"effect": "^4.0.7",
|
|
70
|
-
"@entifix/transactions": "0.23.
|
|
70
|
+
"@entifix/transactions": "0.23.15"
|
|
71
71
|
},
|
|
72
72
|
"peerDependenciesMeta": {
|
|
73
73
|
"@entifix/transactions": {
|