@latticecms/store-mongo 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +171 -2
- package/dist/errors.d.ts +28 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +40 -0
- package/dist/errors.js.map +1 -0
- package/dist/filter.d.ts +20 -0
- package/dist/filter.d.ts.map +1 -0
- package/dist/filter.js +113 -0
- package/dist/filter.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mapper.d.ts +33 -0
- package/dist/mapper.d.ts.map +1 -0
- package/dist/mapper.js +23 -0
- package/dist/mapper.js.map +1 -0
- package/dist/migrate.d.ts +51 -0
- package/dist/migrate.d.ts.map +1 -0
- package/dist/migrate.js +126 -0
- package/dist/migrate.js.map +1 -0
- package/dist/migration-error.d.ts +55 -0
- package/dist/migration-error.d.ts.map +1 -0
- package/dist/migration-error.js +42 -0
- package/dist/migration-error.js.map +1 -0
- package/dist/migration-lock.d.ts +30 -0
- package/dist/migration-lock.d.ts.map +1 -0
- package/dist/migration-lock.js +107 -0
- package/dist/migration-lock.js.map +1 -0
- package/dist/mongo-store.d.ts +58 -0
- package/dist/mongo-store.d.ts.map +1 -0
- package/dist/mongo-store.js +190 -0
- package/dist/mongo-store.js.map +1 -0
- package/dist/operations.d.ts +23 -0
- package/dist/operations.d.ts.map +1 -0
- package/dist/operations.js +149 -0
- package/dist/operations.js.map +1 -0
- package/dist/tracing.d.ts +14 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +54 -0
- package/dist/tracing.js.map +1 -0
- package/package.json +74 -4
- package/src/errors.ts +43 -0
- package/src/filter.ts +127 -0
- package/src/index.ts +10 -0
- package/src/mapper.ts +30 -0
- package/src/migrate.ts +185 -0
- package/src/migration-error.ts +41 -0
- package/src/migration-lock.ts +146 -0
- package/src/mongo-store.ts +303 -0
- package/src/operations.ts +213 -0
- package/src/tracing.ts +64 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type AnyWhere, type FindQuery, type Index, type Page, type Patch, type StoredDoc } from '@latticecms/core/store';
|
|
2
|
+
import type { ClientSession, Db } from 'mongodb';
|
|
3
|
+
import type { MongoDoc } from './mapper.js';
|
|
4
|
+
/**
|
|
5
|
+
* The port's operations on one database, optionally inside a session. The
|
|
6
|
+
* store runs them without one, and a transaction's view of the store with
|
|
7
|
+
* its session, so both share every query.
|
|
8
|
+
*/
|
|
9
|
+
export declare class MongoOperations {
|
|
10
|
+
#private;
|
|
11
|
+
private readonly db;
|
|
12
|
+
private readonly docs;
|
|
13
|
+
constructor(db: Db, docs: MongoDoc, session?: ClientSession);
|
|
14
|
+
ensure(collection: string, indexes: readonly Index[]): Promise<void>;
|
|
15
|
+
find(query: FindQuery): Promise<Page>;
|
|
16
|
+
count(collection: string, where?: AnyWhere): Promise<number>;
|
|
17
|
+
get(collection: string, id: string, where?: AnyWhere): Promise<StoredDoc | null>;
|
|
18
|
+
getMany(collection: string, ids: readonly string[], where?: AnyWhere): Promise<StoredDoc[]>;
|
|
19
|
+
insert(collection: string, doc: StoredDoc): Promise<void>;
|
|
20
|
+
update(collection: string, id: string, patch: Patch, where?: AnyWhere): Promise<StoredDoc | null>;
|
|
21
|
+
remove(collection: string, id: string, where?: AnyWhere): Promise<StoredDoc | null>;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=operations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operations.d.ts","sourceRoot":"","sources":["../src/operations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,QAAQ,EAGb,KAAK,SAAS,EACd,KAAK,KAAK,EAEV,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,SAAS,EACf,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,aAAa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1,149 @@
|
|
|
1
|
+
import { after, encodeCursor, orderOf, } from '@latticecms/core/store';
|
|
2
|
+
import { writing } from './errors.js';
|
|
3
|
+
import { and, mongoField, toFilter, toSort } from './filter.js';
|
|
4
|
+
import { traced } from './tracing.js';
|
|
5
|
+
/**
|
|
6
|
+
* The port's operations on one database, optionally inside a session. The
|
|
7
|
+
* store runs them without one, and a transaction's view of the store with
|
|
8
|
+
* its session, so both share every query.
|
|
9
|
+
*/
|
|
10
|
+
export class MongoOperations {
|
|
11
|
+
db;
|
|
12
|
+
docs;
|
|
13
|
+
#session;
|
|
14
|
+
constructor(db, docs, session) {
|
|
15
|
+
this.db = db;
|
|
16
|
+
this.docs = docs;
|
|
17
|
+
this.#session = session === undefined ? {} : { session };
|
|
18
|
+
}
|
|
19
|
+
#collection(name) {
|
|
20
|
+
return this.db.collection(name);
|
|
21
|
+
}
|
|
22
|
+
#toDoc(doc) {
|
|
23
|
+
return this.docs.fromModel(doc);
|
|
24
|
+
}
|
|
25
|
+
/** `work` as one span, named by the Mongo command it runs. */
|
|
26
|
+
#traced(operation, collection, work) {
|
|
27
|
+
return traced(this.db.databaseName, operation, collection, work);
|
|
28
|
+
}
|
|
29
|
+
async ensure(collection, indexes) {
|
|
30
|
+
return this.#traced('createIndexes', collection, async () => {
|
|
31
|
+
const target = this.#collection(collection);
|
|
32
|
+
// createIndex is a no-op for an index that exists, and rejects one with
|
|
33
|
+
// the same keys and other options (IndexOptionsConflict or
|
|
34
|
+
// IndexKeySpecsConflict), or a unique one over duplicates (11000).
|
|
35
|
+
// Each passes through: changing an index is a migration. An index is
|
|
36
|
+
// never built inside a transaction, so it takes no session.
|
|
37
|
+
for (const index of indexes) {
|
|
38
|
+
const keys = Object.fromEntries(Object.entries(index.fields).map(([field, direction]) => [
|
|
39
|
+
mongoField(field),
|
|
40
|
+
direction,
|
|
41
|
+
]));
|
|
42
|
+
await target.createIndex(keys, index.unique === true ? { unique: true } : {});
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async find(query) {
|
|
47
|
+
return this.#traced('find', query.collection, async () => {
|
|
48
|
+
const target = this.#collection(query.collection);
|
|
49
|
+
const order = orderOf(query.sort);
|
|
50
|
+
// The keyset is a Where, so it is filtered like any other.
|
|
51
|
+
const filter = and(toFilter(query.where), query.after === undefined
|
|
52
|
+
? undefined
|
|
53
|
+
: toFilter(after(order, query.after)));
|
|
54
|
+
// One more than the page tells whether another page follows.
|
|
55
|
+
const window = await target
|
|
56
|
+
.find(filter, this.#session)
|
|
57
|
+
.sort(toSort(order))
|
|
58
|
+
.limit(query.limit + 1)
|
|
59
|
+
.toArray();
|
|
60
|
+
const docs = window.slice(0, query.limit).map((doc) => this.#toDoc(doc));
|
|
61
|
+
const last = docs.at(-1);
|
|
62
|
+
return {
|
|
63
|
+
docs,
|
|
64
|
+
next: window.length > query.limit && last !== undefined
|
|
65
|
+
? encodeCursor(order, last)
|
|
66
|
+
: null,
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
async count(collection, where) {
|
|
71
|
+
return this.#traced('aggregate', collection, async () => {
|
|
72
|
+
return this.#collection(collection).countDocuments(toFilter(where), this.#session);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async get(collection, id, where) {
|
|
76
|
+
return this.#traced('find', collection, async () => {
|
|
77
|
+
const doc = await this.#collection(collection).findOne(byId(id, where), this.#session);
|
|
78
|
+
return doc === null ? null : this.#toDoc(doc);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async getMany(collection, ids, where) {
|
|
82
|
+
return this.#traced('find', collection, async () => {
|
|
83
|
+
const found = await this.#collection(collection)
|
|
84
|
+
.find(and({ _id: { $in: [...ids] } }, toFilter(where)), this.#session)
|
|
85
|
+
.toArray();
|
|
86
|
+
const byKey = new Map(found.map((doc) => [doc._id, doc]));
|
|
87
|
+
return ids.flatMap((id) => {
|
|
88
|
+
const doc = byKey.get(id);
|
|
89
|
+
return doc === undefined ? [] : [this.#toDoc(doc)];
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
async insert(collection, doc) {
|
|
94
|
+
return this.#traced('insert', collection, async () => {
|
|
95
|
+
const target = this.#collection(collection);
|
|
96
|
+
await writing(collection, doc.id, () => target.insertOne(this.docs.toModel(doc), this.#session));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
async update(collection, id, patch, where) {
|
|
100
|
+
return this.#traced('findAndModify', collection, async () => {
|
|
101
|
+
const target = this.#collection(collection);
|
|
102
|
+
const filter = byId(id, where);
|
|
103
|
+
const changes = updateOf(patch);
|
|
104
|
+
if (changes === undefined) {
|
|
105
|
+
const doc = await target.findOne(filter, this.#session);
|
|
106
|
+
return doc === null ? null : this.#toDoc(doc);
|
|
107
|
+
}
|
|
108
|
+
const doc = await writing(collection, id, () => target.findOneAndUpdate(filter, changes, {
|
|
109
|
+
returnDocument: 'after',
|
|
110
|
+
...this.#session,
|
|
111
|
+
}));
|
|
112
|
+
return doc === null ? null : this.#toDoc(doc);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
async remove(collection, id, where) {
|
|
116
|
+
return this.#traced('findAndModify', collection, async () => {
|
|
117
|
+
const doc = await this.#collection(collection).findOneAndDelete(byId(id, where), this.#session);
|
|
118
|
+
return doc === null ? null : this.#toDoc(doc);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** The document `id`, if it is inside `where`. */
|
|
123
|
+
function byId(id, where) {
|
|
124
|
+
return and({ _id: id }, toFilter(where));
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* A patch as a Mongo update: `$set` for each value, `$unset` for each key
|
|
128
|
+
* set to undefined. `id` is never written, even when a JavaScript caller
|
|
129
|
+
* passes one. Undefined when the patch changes nothing.
|
|
130
|
+
*/
|
|
131
|
+
function updateOf(patch) {
|
|
132
|
+
const set = {};
|
|
133
|
+
const unset = {};
|
|
134
|
+
for (const [field, value] of Object.entries(patch)) {
|
|
135
|
+
if (field === 'id')
|
|
136
|
+
continue;
|
|
137
|
+
if (value === undefined)
|
|
138
|
+
unset[field] = '';
|
|
139
|
+
else
|
|
140
|
+
set[field] = value;
|
|
141
|
+
}
|
|
142
|
+
const update = {};
|
|
143
|
+
if (Object.keys(set).length > 0)
|
|
144
|
+
update.$set = set;
|
|
145
|
+
if (Object.keys(unset).length > 0)
|
|
146
|
+
update.$unset = unset;
|
|
147
|
+
return Object.keys(update).length === 0 ? undefined : update;
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=operations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operations.js","sourceRoot":"","sources":["../src/operations.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,EACL,YAAY,EAGZ,OAAO,GAIR,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAEhE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAIP;IACA;IAJV,QAAQ,CAAuC;IAExD,YACmB,EAAM,EACN,IAAc,EAC/B,OAAuB;QAFN,OAAE,GAAF,EAAE,CAAI;QACN,SAAI,GAAJ,IAAI,CAAU;QAG/B,IAAI,CAAC,QAAQ,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC;IAC3D,CAAC;IAED,WAAW,CAAC,IAAY;QACtB,OAAO,IAAI,CAAC,EAAE,CAAC,UAAU,CAAgB,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,CAAC,GAAkB;QACvB,OAAO,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IACl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AAE,CAAC;;YACtC,GAAG,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;IAC1B,CAAC;IACD,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,CAAC,IAAI,GAAG,GAAG,CAAC;IACnD,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC;IACzD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;AAC/D,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's tracer. With no OpenTelemetry SDK registered it is the
|
|
3
|
+
* API's no-op, so tracing costs nothing until an app registers one.
|
|
4
|
+
*/
|
|
5
|
+
export declare const tracer: import("@opentelemetry/api").Tracer;
|
|
6
|
+
/**
|
|
7
|
+
* Runs `work` as one database client span, `{operation} {collection}`, with
|
|
8
|
+
* OpenTelemetry's database attributes. No query text: a Mongo filter has no
|
|
9
|
+
* parameters, so its text would carry the values it matches. A failure is
|
|
10
|
+
* status ERROR with its type, and no exception event: a driver's message
|
|
11
|
+
* can quote a document's values, such as a duplicate key.
|
|
12
|
+
*/
|
|
13
|
+
export declare function traced<T>(database: string, operation: string, collection: string | undefined, work: () => Promise<T>): Promise<T>;
|
|
14
|
+
//# sourceMappingURL=tracing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracing.d.ts","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,eAAO,MAAM,MAAM,qCAAsD,CAAC;AAE1E;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,CAAC,EACtB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACrB,OAAO,CAAC,CAAC,CAAC,CAiCZ"}
|
package/dist/tracing.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { LatticeError } from '@latticecms/core';
|
|
3
|
+
import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
// The package's own version, read from its package.json at runtime, so the
|
|
6
|
+
// tracer's version never drifts from the release. src/ and dist/ both sit
|
|
7
|
+
// one level below it.
|
|
8
|
+
const { version } = z
|
|
9
|
+
.object({ version: z.string() })
|
|
10
|
+
.parse(createRequire(import.meta.url)('../package.json'));
|
|
11
|
+
/**
|
|
12
|
+
* The package's tracer. With no OpenTelemetry SDK registered it is the
|
|
13
|
+
* API's no-op, so tracing costs nothing until an app registers one.
|
|
14
|
+
*/
|
|
15
|
+
export const tracer = trace.getTracer('@latticecms/store-mongo', version);
|
|
16
|
+
/**
|
|
17
|
+
* Runs `work` as one database client span, `{operation} {collection}`, with
|
|
18
|
+
* OpenTelemetry's database attributes. No query text: a Mongo filter has no
|
|
19
|
+
* parameters, so its text would carry the values it matches. A failure is
|
|
20
|
+
* status ERROR with its type, and no exception event: a driver's message
|
|
21
|
+
* can quote a document's values, such as a duplicate key.
|
|
22
|
+
*/
|
|
23
|
+
export function traced(database, operation, collection, work) {
|
|
24
|
+
const name = collection === undefined ? operation : `${operation} ${collection}`;
|
|
25
|
+
return tracer.startActiveSpan(name, {
|
|
26
|
+
kind: SpanKind.CLIENT,
|
|
27
|
+
attributes: {
|
|
28
|
+
'db.system.name': 'mongodb',
|
|
29
|
+
'db.namespace': database,
|
|
30
|
+
'db.operation.name': operation,
|
|
31
|
+
...(collection === undefined
|
|
32
|
+
? {}
|
|
33
|
+
: { 'db.collection.name': collection }),
|
|
34
|
+
},
|
|
35
|
+
}, async (span) => {
|
|
36
|
+
try {
|
|
37
|
+
return await work();
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
const type = LatticeError.is(error)
|
|
41
|
+
? String(error.code)
|
|
42
|
+
: error instanceof Error
|
|
43
|
+
? error.name
|
|
44
|
+
: typeof error;
|
|
45
|
+
span.setAttribute('error.type', type);
|
|
46
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: type });
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
span.end();
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=tracing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracing.js","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,2EAA2E;AAC3E,0EAA0E;AAC1E,sBAAsB;AACtB,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC;KAClB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;KAC/B,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC;AAE5D;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,yBAAyB,EAAE,OAAO,CAAC,CAAC;AAE1E;;;;;;GAMG;AACH,MAAM,UAAU,MAAM,CACpB,QAAgB,EAChB,SAAiB,EACjB,UAA8B,EAC9B,IAAsB;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6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The MongoDB CollectionStore for Lattice CMS.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"lattice",
|
|
7
|
+
"cms",
|
|
8
|
+
"mongodb",
|
|
9
|
+
"store",
|
|
10
|
+
"migrations"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/crobinson42/lattice-cms.git",
|
|
18
|
+
"directory": "packages/store-mongo"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/crobinson42/lattice-cms/tree/main/packages/store-mongo#readme",
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/crobinson42/lattice-cms/issues"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist",
|
|
34
|
+
"src",
|
|
35
|
+
"!src/**/*.test.ts",
|
|
36
|
+
"!src/test"
|
|
37
|
+
],
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=22.11"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "tsc -b",
|
|
46
|
+
"test": "vitest run",
|
|
47
|
+
"type-check": "tsc --noEmit -p tsconfig.check.json && tsc -p tsconfig.dist.json",
|
|
48
|
+
"lint": "biome check .",
|
|
49
|
+
"clean": "rm -rf dist *.tsbuildinfo"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"mongodb": "^7.9.1"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"@hexok/logger": "^0.2.0",
|
|
56
|
+
"@latticecms/core": "^0.1.0",
|
|
57
|
+
"@opentelemetry/api": "^1.3.0",
|
|
58
|
+
"hexok": "^2.2.7",
|
|
59
|
+
"zod": "^4.1.0"
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@hexok/logger": "^0.2.0",
|
|
63
|
+
"@latticecms/core": "*",
|
|
64
|
+
"@opentelemetry/api": "~1.9.1",
|
|
65
|
+
"@opentelemetry/context-async-hooks": "^2.12.1",
|
|
66
|
+
"@opentelemetry/sdk-trace-base": "^2.12.1",
|
|
67
|
+
"hexok": "^2.2.7",
|
|
68
|
+
"mongodb-memory-server": "^11.3.0",
|
|
69
|
+
"zod": "^4.1.0"
|
|
70
|
+
},
|
|
71
|
+
"config": {
|
|
72
|
+
"mongodbMemoryServer": {
|
|
73
|
+
"version": "8.0.14"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { LatticeError } from '@latticecms/core';
|
|
2
|
+
import { Errors } from 'hexok';
|
|
3
|
+
import { MongoServerError } from 'mongodb';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A call at the wrong time in the store's lifecycle. The codes are
|
|
7
|
+
* ioredis-lifecycle's, so an app matches every adapter's on `code`. Fix
|
|
8
|
+
* the call order; do not retry.
|
|
9
|
+
*/
|
|
10
|
+
export class MongoStoreError extends Errors('store-mongo', {
|
|
11
|
+
NotStarted: {
|
|
12
|
+
message: 'MongoStore: start() has not been called. Await start() first.',
|
|
13
|
+
},
|
|
14
|
+
Starting: {
|
|
15
|
+
message: 'MongoStore: start() has not finished. Await start() first.',
|
|
16
|
+
},
|
|
17
|
+
Stopped: {
|
|
18
|
+
message: 'MongoStore: stop() was called. Start it again to use it.',
|
|
19
|
+
},
|
|
20
|
+
}) {}
|
|
21
|
+
|
|
22
|
+
/** A duplicate key on a write: an id clash or a unique index. */
|
|
23
|
+
export function isDuplicateKey(error: unknown): boolean {
|
|
24
|
+
return error instanceof MongoServerError && error.code === 11000;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Runs a write of the document `id`, turning a duplicate key into Lattice's
|
|
29
|
+
* CONFLICT for that document. `id` is the document being written, which
|
|
30
|
+
* the caller always knows, so the driver's message is never parsed.
|
|
31
|
+
*/
|
|
32
|
+
export async function writing<T>(
|
|
33
|
+
collection: string,
|
|
34
|
+
id: string,
|
|
35
|
+
write: () => Promise<T>,
|
|
36
|
+
): Promise<T> {
|
|
37
|
+
try {
|
|
38
|
+
return await write();
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (isDuplicateKey(error)) throw LatticeError.CONFLICT({ collection, id });
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/filter.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { AnyWhere, FieldOps, Order } from '@latticecms/core/store';
|
|
2
|
+
import type { Document } from 'mongodb';
|
|
3
|
+
|
|
4
|
+
/** The Mongo field that holds a Lattice field: `id` is kept in `_id`. */
|
|
5
|
+
export function mongoField(field: string): string {
|
|
6
|
+
return field === 'id' ? '_id' : field;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** `text` with every regex metacharacter escaped, so it matches literally. */
|
|
10
|
+
export function escapeRegex(text: string): string {
|
|
11
|
+
return text.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Both filters. Never merged by spreading: two filters can name the same
|
|
16
|
+
* field, and a spread would let one replace the other's condition.
|
|
17
|
+
*/
|
|
18
|
+
export function and(...filters: readonly (Document | undefined)[]): Document {
|
|
19
|
+
const present = filters.filter(
|
|
20
|
+
(filter): filter is Document =>
|
|
21
|
+
filter !== undefined && Object.keys(filter).length > 0,
|
|
22
|
+
);
|
|
23
|
+
if (present.length === 0) return {};
|
|
24
|
+
if (present.length === 1) return present[0] ?? {};
|
|
25
|
+
return { $and: present };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Matches no document. Mongo rejects an empty `$or`; the matcher finds nothing. */
|
|
29
|
+
const nothing: Document = { $expr: false };
|
|
30
|
+
|
|
31
|
+
/** The Mongo conditions of one field's operators, each as `[operator, value]`. */
|
|
32
|
+
function conditions(ops: FieldOps): [string, unknown][] {
|
|
33
|
+
const out: [string, unknown][] = [];
|
|
34
|
+
for (const [op, value] of Object.entries(ops)) {
|
|
35
|
+
if (value === undefined) continue;
|
|
36
|
+
switch (op) {
|
|
37
|
+
case 'eq':
|
|
38
|
+
case 'ne':
|
|
39
|
+
case 'in':
|
|
40
|
+
case 'nin':
|
|
41
|
+
case 'gt':
|
|
42
|
+
case 'gte':
|
|
43
|
+
case 'lt':
|
|
44
|
+
case 'lte':
|
|
45
|
+
out.push([`$${op}`, value]);
|
|
46
|
+
break;
|
|
47
|
+
case 'contains':
|
|
48
|
+
// Case-insensitive and literal, never a pattern. A regex matches
|
|
49
|
+
// strings only, as `contains` does.
|
|
50
|
+
out.push(['$regex', escapeRegex(String(value))], ['$options', 'i']);
|
|
51
|
+
break;
|
|
52
|
+
case 'has':
|
|
53
|
+
// On an array field, Mongo's equality matches any element.
|
|
54
|
+
out.push(['$eq', value]);
|
|
55
|
+
break;
|
|
56
|
+
case 'exists':
|
|
57
|
+
// Lattice's exists asks whether a field has a value, so null does
|
|
58
|
+
// not exist. Mongo's $exists would count null as present.
|
|
59
|
+
out.push(value === true ? ['$ne', null] : ['$eq', null]);
|
|
60
|
+
break;
|
|
61
|
+
default:
|
|
62
|
+
throw new Error(`MongoStore: unknown operator "${op}"`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The filter for one field. Its operators share one object, unless two map
|
|
70
|
+
* to the same Mongo operator (`ne` with `exists: true`), when each gets its
|
|
71
|
+
* own clause.
|
|
72
|
+
*/
|
|
73
|
+
function fieldFilter(field: string, ops: FieldOps): Document {
|
|
74
|
+
const name = mongoField(field);
|
|
75
|
+
const pairs = conditions(ops);
|
|
76
|
+
const operators = pairs.map(([op]) => op);
|
|
77
|
+
if (new Set(operators).size === operators.length) {
|
|
78
|
+
return { [name]: Object.fromEntries(pairs) };
|
|
79
|
+
}
|
|
80
|
+
return and(
|
|
81
|
+
...pairs
|
|
82
|
+
.filter(([op]) => op !== '$options')
|
|
83
|
+
.map(([op, value]) =>
|
|
84
|
+
op === '$regex'
|
|
85
|
+
? { [name]: { $regex: value, $options: 'i' } }
|
|
86
|
+
: { [name]: { [op]: value } },
|
|
87
|
+
),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isClauses(
|
|
92
|
+
condition: FieldOps | readonly AnyWhere[],
|
|
93
|
+
): condition is readonly AnyWhere[] {
|
|
94
|
+
return Array.isArray(condition);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A parsed `Where` as a Mongo filter, one to one: the matcher already
|
|
99
|
+
* follows Mongo's null and missing rules. Fields become one object, which
|
|
100
|
+
* Mongo ANDs; `and` and `or` become `$and` and `$or`.
|
|
101
|
+
*/
|
|
102
|
+
export function toFilter(where: AnyWhere | undefined): Document {
|
|
103
|
+
if (where === undefined) return {};
|
|
104
|
+
const fields: Document[] = [];
|
|
105
|
+
const clauses: Document[] = [];
|
|
106
|
+
for (const [field, condition] of Object.entries(where)) {
|
|
107
|
+
if (condition === undefined) continue;
|
|
108
|
+
if (!isClauses(condition)) {
|
|
109
|
+
fields.push(fieldFilter(field, condition));
|
|
110
|
+
} else if (field === 'and') {
|
|
111
|
+
clauses.push(...condition.map(toFilter));
|
|
112
|
+
} else {
|
|
113
|
+
clauses.push(
|
|
114
|
+
condition.length === 0 ? nothing : { $or: condition.map(toFilter) },
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Each field is named once, so field filters without `$and` merge.
|
|
119
|
+
const simple = fields.filter((filter) => !('$and' in filter));
|
|
120
|
+
const nested = fields.filter((filter) => '$and' in filter);
|
|
121
|
+
return and(Object.assign({}, ...simple), ...nested, ...clauses);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A Lattice order as a Mongo sort spec, in key order. */
|
|
125
|
+
export function toSort(order: Order): [string, 1 | -1][] {
|
|
126
|
+
return order.map(({ field, direction }) => [mongoField(field), direction]);
|
|
127
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { MongoStoreError } from './errors.js';
|
|
2
|
+
export {
|
|
3
|
+
type MigrateOptions,
|
|
4
|
+
type Migration,
|
|
5
|
+
type MigrationContext,
|
|
6
|
+
migrate,
|
|
7
|
+
type Ran,
|
|
8
|
+
} from './migrate.js';
|
|
9
|
+
export { MigrationError } from './migration-error.js';
|
|
10
|
+
export { MongoStore, type MongoStoreOptions } from './mongo-store.js';
|
package/src/mapper.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { StoredDoc } from '@latticecms/core/store';
|
|
2
|
+
import { Mapper } from 'hexok';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
/** A document as Lattice stores it: `id` and any fields. */
|
|
6
|
+
const storedDoc = z.looseObject({ id: z.string() });
|
|
7
|
+
|
|
8
|
+
/** The same document in MongoDB: `id` kept in `_id`, as a string. */
|
|
9
|
+
const mongoDoc = z.looseObject({ _id: z.string() });
|
|
10
|
+
|
|
11
|
+
/** A Mongo document as the driver reads and writes it. */
|
|
12
|
+
export type MongoDocument = z.output<typeof mongoDoc>;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Maps a `StoredDoc` to its Mongo document and back. Only `id` moves; every
|
|
16
|
+
* other field keeps its name and value. Each direction builds a new object,
|
|
17
|
+
* so the driver's insert, which adds `_id` to what it is given, never
|
|
18
|
+
* touches the caller's document.
|
|
19
|
+
*/
|
|
20
|
+
export class MongoDoc extends Mapper('mongo.StoredDoc', storedDoc, mongoDoc) {
|
|
21
|
+
protected fromSource(doc: StoredDoc): MongoDocument {
|
|
22
|
+
const { id, ...fields } = doc;
|
|
23
|
+
return { ...fields, _id: id };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
protected toSource(doc: MongoDocument): StoredDoc {
|
|
27
|
+
const { _id, ...fields } = doc;
|
|
28
|
+
return { ...fields, id: _id };
|
|
29
|
+
}
|
|
30
|
+
}
|