@entifix/mongo 0.22.4 → 0.23.1
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 +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,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,
|
|
1
|
+
{"version":3,"file":"make-mongo-repository.d.ts","sourceRoot":"","sources":["../../src/adapters/make-mongo-repository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAIL,MAAM,EACN,iBAAiB,EASlB,MAAM,eAAe,CAAC;AAEvB,OAAO,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAQjD,kFAAkF;AAClF,wBAAgB,mBAAmB,CAAC,OAAO,SAAS,MAAM,EACxD,iBAAiB,EAAE,iBAAiB,CAAC,OAAO,CAAC,GAC5C,MAAM,CAGR;AA4BD;;;;;;;;;;;;;;;;;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,CAsKlB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import { deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, NotFound, serializeEntity } from '@entifix/core';
|
|
3
|
+
import { declaresRevision, deserializeEntityCollection, deserializeSingleEntity, extractMetaEntity, NotFound, readRevision, serializeEntity, StaleRevision } from '@entifix/core';
|
|
4
4
|
import { Effect } from 'effect';
|
|
5
5
|
import { translateMongoError } from '../errors/translate-mongo-error.js';
|
|
6
6
|
import { translateFiltering, translateSorting } from './filter-translator.js';
|
|
@@ -14,6 +14,27 @@ import { translateFiltering, translateSorting } from './filter-translator.js';
|
|
|
14
14
|
const metaEntity = extractMetaEntity(entityConstructor);
|
|
15
15
|
return (_metaEntity_key = metaEntity.key) != null ? _metaEntity_key : metaEntity.name;
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* The collections whose unique index on `id` is known to exist, per database.
|
|
19
|
+
* A create is atomic only against that index: two concurrent creates of one
|
|
20
|
+
* client-minted id would otherwise both insert. Keyed on the `Db` so a fake or
|
|
21
|
+
* a reset database starts clean, and a rejected attempt is forgotten so the
|
|
22
|
+
* next create tries again.
|
|
23
|
+
*/ const ensuredIdIndexes = new WeakMap();
|
|
24
|
+
const ensureIdIndex = (db, name)=>Effect.suspend(()=>{
|
|
25
|
+
var _ensuredIdIndexes_get;
|
|
26
|
+
const ensured = (_ensuredIdIndexes_get = ensuredIdIndexes.get(db)) != null ? _ensuredIdIndexes_get : new Set();
|
|
27
|
+
ensuredIdIndexes.set(db, ensured);
|
|
28
|
+
if (ensured.has(name)) return Effect.void;
|
|
29
|
+
return Effect.tryPromise({
|
|
30
|
+
try: ()=>db.collection(name).createIndex({
|
|
31
|
+
id: 1
|
|
32
|
+
}, {
|
|
33
|
+
unique: true
|
|
34
|
+
}),
|
|
35
|
+
catch: (error)=>translateMongoError(error)
|
|
36
|
+
}).pipe(Effect.tap(()=>Effect.sync(()=>ensured.add(name))));
|
|
37
|
+
});
|
|
17
38
|
function toEntityId(entityOrId) {
|
|
18
39
|
return entityOrId != null && typeof entityOrId === 'object' ? entityOrId.id : entityOrId;
|
|
19
40
|
}
|
|
@@ -35,7 +56,8 @@ function toEntityId(entityOrId) {
|
|
|
35
56
|
* work's handle — so its writes commit with the unit and its reads see what the
|
|
36
57
|
* unit has already written.
|
|
37
58
|
*/ export function makeMongoRepository(db, entityConstructor, options) {
|
|
38
|
-
const
|
|
59
|
+
const collectionName = mongoCollectionName(entityConstructor);
|
|
60
|
+
const collection = db.collection(collectionName);
|
|
39
61
|
// Spread into every call, so a repository with no session passes none.
|
|
40
62
|
const inSession = (options == null ? void 0 : options.session) ? {
|
|
41
63
|
session: options.session
|
|
@@ -77,7 +99,68 @@ function toEntityId(entityOrId) {
|
|
|
77
99
|
}
|
|
78
100
|
return entity;
|
|
79
101
|
});
|
|
80
|
-
const
|
|
102
|
+
const revised = declaresRevision(entityConstructor);
|
|
103
|
+
/**
|
|
104
|
+
* A save of an entity that declares a revision (ADR 0032): a create that
|
|
105
|
+
* never overwrites, or one conditional write on the revision the caller read.
|
|
106
|
+
* Never a read followed by a write — two saves would both read `n`.
|
|
107
|
+
*/ const saveRevised = (entity)=>Effect.gen(function*() {
|
|
108
|
+
var _entity_id;
|
|
109
|
+
const key = extractMetaEntity(entityConstructor).key;
|
|
110
|
+
const doc = serializeEntity(entityConstructor, entity);
|
|
111
|
+
const read = readRevision(entity);
|
|
112
|
+
const id = (_entity_id = entity.id) != null ? _entity_id : randomUUID();
|
|
113
|
+
if (read === undefined) {
|
|
114
|
+
yield* ensureIdIndex(db, collectionName);
|
|
115
|
+
yield* Effect.tryPromise({
|
|
116
|
+
try: ()=>collection.insertOne(_extends({}, doc, {
|
|
117
|
+
id,
|
|
118
|
+
revision: 1
|
|
119
|
+
}), inSession),
|
|
120
|
+
catch: (error)=>translateMongoError(error)
|
|
121
|
+
}).pipe(Effect.mapError((failure)=>failure._tag === 'DuplicateKey' ? new StaleRevision({
|
|
122
|
+
entity: key
|
|
123
|
+
}) : failure));
|
|
124
|
+
entity.id = id;
|
|
125
|
+
entity.revision = 1;
|
|
126
|
+
return entity;
|
|
127
|
+
}
|
|
128
|
+
const result = yield* Effect.tryPromise({
|
|
129
|
+
try: ()=>collection.replaceOne({
|
|
130
|
+
id,
|
|
131
|
+
revision: read
|
|
132
|
+
}, _extends({}, doc, {
|
|
133
|
+
id,
|
|
134
|
+
revision: read + 1
|
|
135
|
+
}), inSession),
|
|
136
|
+
catch: (error)=>translateMongoError(error)
|
|
137
|
+
});
|
|
138
|
+
if (result.matchedCount === 0) {
|
|
139
|
+
// The write already decided; this read only names the refusal.
|
|
140
|
+
const stored = yield* Effect.tryPromise({
|
|
141
|
+
try: ()=>collection.findOne({
|
|
142
|
+
id
|
|
143
|
+
}, _extends({
|
|
144
|
+
projection: {
|
|
145
|
+
_id: 0,
|
|
146
|
+
revision: 1
|
|
147
|
+
}
|
|
148
|
+
}, inSession)),
|
|
149
|
+
catch: (error)=>translateMongoError(error)
|
|
150
|
+
});
|
|
151
|
+
return yield* stored === null ? Effect.fail(new NotFound({
|
|
152
|
+
entity: key
|
|
153
|
+
})) : Effect.fail(new StaleRevision({
|
|
154
|
+
entity: key,
|
|
155
|
+
current: readRevision(stored)
|
|
156
|
+
}));
|
|
157
|
+
}
|
|
158
|
+
entity.id = id;
|
|
159
|
+
entity.revision = read + 1;
|
|
160
|
+
return entity;
|
|
161
|
+
});
|
|
162
|
+
const save = (entity)=>revised ? saveRevised(entity) : saveUnchecked(entity);
|
|
163
|
+
const saveUnchecked = (entity)=>Effect.gen(function*() {
|
|
81
164
|
var _entity_id;
|
|
82
165
|
const doc = serializeEntity(entityConstructor, entity);
|
|
83
166
|
// A create arrives without an id, so the store mints one. Entities are
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/make-mongo-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository } from '@entifix/business';\nimport {\n deserializeEntityCollection,\n deserializeSingleEntity,\n Entity,\n EntityConstructor,\n EntityId,\n EntityLoadRequest,\n EntityPage,\n extractMetaEntity,\n NotFound,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport { translateFiltering, translateSorting } 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\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 collection = db.collection(mongoCollectionName(entityConstructor));\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 const docs = yield* Effect.tryPromise({\n try: () =>\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 save = <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>(entityOrId: EntityId | T) =>\n Effect.gen(function* () {\n const id = toEntityId(entityOrId);\n yield* Effect.tryPromise({\n try: () => collection.deleteOne({ id }, inSession),\n catch: error => translateMongoError(error),\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","deserializeEntityCollection","deserializeSingleEntity","extractMetaEntity","NotFound","serializeEntity","Effect","translateMongoError","translateFiltering","translateSorting","WITHOUT_MONGO_ID","projection","_id","mongoCollectionName","entityConstructor","metaEntity","key","name","toEntityId","entityOrId","id","makeMongoRepository","db","options","collection","inSession","session","load","request","gen","filter","filtering","sort","sorting","page","pageSize","skip","docs","tryPromise","try","find","limit","toArray","catch","error","total","countDocuments","items","get","doc","findOne","entity","undefined","fail","save","replaceOne","upsert","del","deleteOne","delete"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,2BAA2B,EAC3BC,uBAAuB,EAMvBC,iBAAiB,EACjBC,QAAQ,EACRC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,yBAAyB;AAE9E,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAaZ,kBAAkBW;IACrC,QAAOC,kBAAAA,WAAWC,GAAG,YAAdD,kBAAkBA,WAAWE,IAAI;AAC1C;AAEA,SAASC,WAAWC,UAA6B;IAC/C,OAAOA,cAAc,QAAQ,OAAOA,eAAe,WAC/C,AAACA,WAAsBC,EAAE,GACxBD;AACP;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASE,oBACdC,EAAM,EACNR,iBAA6C,EAC7CS,OAA8C;IAE9C,MAAMC,aAAaF,GAAGE,UAAU,CAACX,oBAAoBC;IACrD,uEAAuE;IACvE,MAAMW,YAAYF,CAAAA,2BAAAA,QAASG,OAAO,IAAG;QAAEA,SAASH,QAAQG,OAAO;IAAC,IAAI,CAAC;IAErE,MAAMC,OAAO,CAAmBC,UAC9BtB,OAAOuB,GAAG,CAAC;gBAGID,eACIA;YAHjB,MAAME,SAAStB,mBAAmBoB,QAAQG,SAAS;YACnD,MAAMC,OAAOvB,iB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ACvE,sEAAsE;YACtE,8DAA8D;YAC9D,sDAAsD;YACtD,MAAM/B,MAAK+B,aAAAA,OAAO/B,EAAE,YAAT+B,aAAanD;YACxB,OAAOM,OAAOgC,UAAU,CAAC;gBACvB,+DAA+D;gBAC/D,uDAAuD;gBACvDC,KAAK,IACHf,WAAW+B,UAAU,CACnB;wBAAEnC;oBAAG,GACL,aAAK6B;wBAAK7B;wBACV;wBAAEoC,QAAQ;uBAAS/B;gBAEvBkB,OAAOC,CAAAA,QAASrC,oBAAoBqC;YACtC;YACAO,OAAO/B,EAAE,GAAGA;YACZ,OAAO+B;QACT;IAEF,MAAMM,MAAM,CAAmBtC,aAC7Bb,OAAOuB,GAAG,CAAC;YACT,MAAMT,KAAKF,WAAWC;YACtB,OAAOb,OAAOgC,UAAU,CAAC;gBACvBC,KAAK,IAAMf,WAAWkC,SAAS,CAAC;wBAAEtC;oBAAG,GAAGK;gBACxCkB,OAAOC,CAAAA,QAASrC,oBAAoBqC;YACtC;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACLjB;QACAqB;QACAM;QACAK,QAAQF;IACV;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/make-mongo-repository.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { EntityRepository } from '@entifix/business';\nimport {\n declaresRevision,\n deserializeEntityCollection,\n deserializeSingleEntity,\n Entity,\n EntityConstructor,\n EntityId,\n EntityLoadRequest,\n EntityPage,\n extractMetaEntity,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { ClientSession, Db } from 'mongodb';\n\nimport { translateMongoError } from '../errors/translate-mongo-error.js';\nimport { translateFiltering, translateSorting } 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 const docs = yield* Effect.tryPromise({\n try: () =>\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 /**\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>(entity: T) =>\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 },\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.\n const stored = yield* Effect.tryPromise({\n try: () =>\n collection.findOne(\n { id },\n { projection: { _id: 0, revision: 1 }, ...inSession },\n ),\n catch: error => translateMongoError(error),\n });\n return yield* stored === null\n ? Effect.fail(new NotFound({ entity: key }))\n : 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) =>\n revised ? saveRevised(entity) : saveUnchecked(entity);\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>(entityOrId: EntityId | T) =>\n Effect.gen(function* () {\n const id = toEntityId(entityOrId);\n yield* Effect.tryPromise({\n try: () => collection.deleteOne({ id }, inSession),\n catch: error => translateMongoError(error),\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","NotFound","readRevision","serializeEntity","StaleRevision","Effect","translateMongoError","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","find","limit","toArray","total","countDocuments","items","doc","findOne","entity","undefined","fail","revised","saveRevised","read","insertOne","revision","mapError","failure","_tag","result","replaceOne","matchedCount","stored","current","save","saveUnchecked","upsert","del","deleteOne","delete"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAGzC,SACEC,gBAAgB,EAChBC,2BAA2B,EAC3BC,uBAAuB,EAMvBC,iBAAiB,EACjBC,QAAQ,EACRC,YAAY,EACZC,eAAe,EACfC,aAAa,QACR,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,mBAAmB,QAAQ,qCAAqC;AACzE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,yBAAyB;AAE9E,oEAAoE,GACpE,MAAMC,mBAAmB;IAAEC,YAAY;QAAEC,KAAK;IAAE;AAAE;AAElD,gFAAgF,GAChF,OAAO,SAASC,oBACdC,iBAA6C;QAGtCC;IADP,MAAMA,aAAad,kBAAkBa;IACrC,QAAOC,kBAAAA,WAAWC,GAAG,YAAdD,kBAAkBA,WAAWE,IAAI;AAC1C;AAEA;;;;;;CAMC,GACD,MAAMC,mBAAmB,IAAIC;AAE7B,MAAMC,gBAAgB,CAACC,IAAQJ,OAC7BX,OAAOgB,OAAO,CAAC;YACGJ;QAAhB,MAAMK,WAAUL,wBAAAA,iBAAiBM,GAAG,CAACH,eAArBH,wBAA4B,IAAIO;QAChDP,iBAAiBQ,GAAG,CAAC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,mBACAqD;YAEF,uEAAuE;YACvE,sEAAsE;YACtE,8DAA8D;YAC9D,sDAAsD;YACtD,MAAMlC,MAAKkC,aAAAA,OAAOlC,EAAE,YAATkC,aAAatE;YACxB,OAAOS,OAAOuB,UAAU,CAAC;gBACvB,+DAA+D;gBAC/D,uDAAuD;gBACvDC,KAAK,IACHC,WAAWgD,UAAU,CACnB;wBAAE9C;oBAAG,GACL,aAAKgC;wBAAKhC;wBACV;wBAAEoD,QAAQ;uBAASvC;gBAEvBX,OAAOC,CAAAA,QAAS7B,oBAAoB6B;YACtC;YACA+B,OAAOlC,EAAE,GAAGA;YACZ,OAAOkC;QACT;IAEF,MAAMmB,MAAM,CAAmB5C,aAC7BpC,OAAO4C,GAAG,CAAC;YACT,MAAMjB,KAAKQ,WAAWC;YACtB,OAAOpC,OAAOuB,UAAU,CAAC;gBACvBC,KAAK,IAAMC,WAAWwD,SAAS,CAAC;wBAAEtD;oBAAG,GAAGa;gBACxCX,OAAOC,CAAAA,QAAS7B,oBAAoB6B;YACtC;QACF;IAEF,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO;QACLY;QACAxB;QACA2D;QACAK,QAAQF;IACV;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/mongo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.1",
|
|
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": {
|
|
@@ -56,18 +56,18 @@
|
|
|
56
56
|
},
|
|
57
57
|
"dependencies": {
|
|
58
58
|
"@swc/helpers": "0.5.23",
|
|
59
|
-
"mongodb": "7.
|
|
60
|
-
"@entifix/
|
|
61
|
-
"@entifix/
|
|
59
|
+
"mongodb": "7.9.0",
|
|
60
|
+
"@entifix/business": "0.23.1",
|
|
61
|
+
"@entifix/core": "0.23.1"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
|
64
64
|
"effect": "4.0.7",
|
|
65
|
-
"@entifix/testing-unit": "0.
|
|
66
|
-
"@entifix/transactions": "0.
|
|
65
|
+
"@entifix/testing-unit": "0.23.1",
|
|
66
|
+
"@entifix/transactions": "0.23.1"
|
|
67
67
|
},
|
|
68
68
|
"peerDependencies": {
|
|
69
69
|
"effect": "^4.0.7",
|
|
70
|
-
"@entifix/transactions": "0.
|
|
70
|
+
"@entifix/transactions": "0.23.1"
|
|
71
71
|
},
|
|
72
72
|
"peerDependenciesMeta": {
|
|
73
73
|
"@entifix/transactions": {
|