@graphql-mesh/transport-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/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # @graphql-mesh/transport-mongo
2
+
3
+ ## 0.1.0
4
+
5
+ ### Major Changes
6
+
7
+ - Initial draft: execute `@mongo` FIND_ONE / FIND_MANY / COUNT from Connectors-style
8
+ `where` / `selection` mappings via the native MongoDB driver (no Mongoose at runtime).
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createMongoClient = createMongoClient;
4
+ const mongodb_1 = require("mongodb");
5
+ function createMongoClient(opts) {
6
+ const client = new mongodb_1.MongoClient(opts.location, {
7
+ maxPoolSize: opts.maxPoolSize,
8
+ });
9
+ let dbPromise;
10
+ async function getDb() {
11
+ if (!dbPromise) {
12
+ dbPromise = client.connect().then(() => client.db());
13
+ }
14
+ return dbPromise;
15
+ }
16
+ return {
17
+ async findOne(collection, filter, options) {
18
+ const db = await getDb();
19
+ return db.collection(collection).findOne(filter, {
20
+ projection: options?.projection,
21
+ sort: options?.sort,
22
+ });
23
+ },
24
+ async findMany(collection, filter, options) {
25
+ const db = await getDb();
26
+ let cursor = db.collection(collection).find(filter, {
27
+ projection: options?.projection,
28
+ sort: options?.sort,
29
+ });
30
+ if (options?.skip != null)
31
+ cursor = cursor.skip(options.skip);
32
+ if (options?.limit != null)
33
+ cursor = cursor.limit(options.limit);
34
+ return cursor.toArray();
35
+ },
36
+ async count(collection, filter) {
37
+ const db = await getDb();
38
+ return db.collection(collection).countDocuments(filter);
39
+ },
40
+ async insertOne(collection, doc) {
41
+ const db = await getDb();
42
+ const result = await db.collection(collection).insertOne(doc);
43
+ return { insertedId: result.insertedId };
44
+ },
45
+ async insertMany(collection, docs) {
46
+ const db = await getDb();
47
+ const result = await db.collection(collection).insertMany(docs);
48
+ return {
49
+ insertedIds: Object.values(result.insertedIds),
50
+ insertedCount: result.insertedCount,
51
+ };
52
+ },
53
+ async updateOne(collection, filter, update) {
54
+ const db = await getDb();
55
+ const result = await db.collection(collection).updateOne(filter, update);
56
+ return {
57
+ matchedCount: result.matchedCount,
58
+ modifiedCount: result.modifiedCount,
59
+ upsertedId: result.upsertedId ?? undefined,
60
+ };
61
+ },
62
+ async updateMany(collection, filter, update) {
63
+ const db = await getDb();
64
+ const result = await db.collection(collection).updateMany(filter, update);
65
+ return {
66
+ matchedCount: result.matchedCount,
67
+ modifiedCount: result.modifiedCount,
68
+ };
69
+ },
70
+ async deleteOne(collection, filter) {
71
+ const db = await getDb();
72
+ const result = await db.collection(collection).deleteOne(filter);
73
+ return { deletedCount: result.deletedCount ?? 0 };
74
+ },
75
+ async deleteMany(collection, filter) {
76
+ const db = await getDb();
77
+ const result = await db.collection(collection).deleteMany(filter);
78
+ return { deletedCount: result.deletedCount ?? 0 };
79
+ },
80
+ async aggregate(collection, pipeline) {
81
+ const db = await getDb();
82
+ return db.collection(collection).aggregate(pipeline).toArray();
83
+ },
84
+ async dispose() {
85
+ await client.close();
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMongoExecutor = getMongoExecutor;
4
+ const transport_common_1 = require("@graphql-mesh/transport-common");
5
+ const utils_1 = require("@graphql-tools/utils");
6
+ const disposablestack_1 = require("@whatwg-node/disposablestack");
7
+ const client_js_1 = require("./client.js");
8
+ const filter_js_1 = require("./filter.js");
9
+ const mapping_js_1 = require("./mapping.js");
10
+ function getMongoExecutor({ subgraph, client }) {
11
+ const transportDirectives = (0, utils_1.getDirective)(subgraph, subgraph, 'transport');
12
+ if (!transportDirectives?.length && !client) {
13
+ throw new Error('No @transport directive found on schema definition');
14
+ }
15
+ const transport = transportDirectives?.[0];
16
+ const mongoClient = client ||
17
+ (0, client_js_1.createMongoClient)({
18
+ location: transport.location,
19
+ ...(transport?.options || {}),
20
+ });
21
+ const executable = (0, utils_1.mapSchema)(subgraph, {
22
+ [utils_1.MapperKind.OBJECT_FIELD](fieldConfig) {
23
+ const mongoDirs = (0, utils_1.getDirective)(subgraph, fieldConfig, 'mongo');
24
+ if (!mongoDirs?.length)
25
+ return fieldConfig;
26
+ return attachMongoResolver(fieldConfig, mongoDirs[0], mongoClient);
27
+ },
28
+ });
29
+ const defaultExecutor = (0, transport_common_1.createDefaultExecutor)(executable);
30
+ const disposable = defaultExecutor;
31
+ disposable[disposablestack_1.DisposableSymbols.asyncDispose] = async () => {
32
+ await mongoClient.dispose();
33
+ };
34
+ return disposable;
35
+ }
36
+ function attachMongoResolver(fieldConfig, directive, client) {
37
+ const selection = (0, mapping_js_1.parseMongoMapping)(directive.selection);
38
+ const projection = (0, mapping_js_1.projectionFromSelection)(selection);
39
+ const filterSource = directive.filter ?? directive.where;
40
+ fieldConfig.resolve = async function mongoResolver(parent, graphqlArgs) {
41
+ const ctx = { args: graphqlArgs, parent };
42
+ const filter = (0, filter_js_1.buildMongoFilter)(filterSource, ctx);
43
+ const sort = (0, filter_js_1.buildMongoSort)(directive.sort, ctx);
44
+ const proj = Object.keys(projection).length ? projection : undefined;
45
+ switch (directive.kind) {
46
+ case 'FIND_ONE': {
47
+ const doc = await client.findOne(directive.collection, filter, {
48
+ projection: proj,
49
+ sort,
50
+ skip: resolveBinderNumber(directive.skip, ctx),
51
+ });
52
+ return (0, mapping_js_1.mapDocumentToGraphql)(doc, selection);
53
+ }
54
+ case 'FIND_MANY': {
55
+ const docs = await client.findMany(directive.collection, filter, {
56
+ projection: proj,
57
+ sort,
58
+ limit: resolveBinderNumber(directive.limit, ctx),
59
+ skip: resolveBinderNumber(directive.skip, ctx),
60
+ });
61
+ return docs.map(doc => (0, mapping_js_1.mapDocumentToGraphql)(doc, selection));
62
+ }
63
+ case 'COUNT':
64
+ return client.count(directive.collection, filter);
65
+ case 'CONNECTION':
66
+ return resolveConnection(client, directive, filter, sort, proj, ctx, selection);
67
+ case 'PAGINATION':
68
+ return resolvePagination(client, directive, filter, sort, proj, ctx, selection);
69
+ case 'INSERT_ONE': {
70
+ const doc = (0, filter_js_1.buildSetDocument)(directive.set, ctx);
71
+ const { insertedId } = await client.insertOne(directive.collection, doc);
72
+ const created = await client.findOne(directive.collection, { _id: insertedId });
73
+ return mapPayload(created, insertedId, selection);
74
+ }
75
+ case 'INSERT_MANY': {
76
+ const records = (graphqlArgs.records || []);
77
+ const { insertedIds, insertedCount } = await client.insertMany(directive.collection, records);
78
+ const docs = await client.findMany(directive.collection, {
79
+ _id: { $in: insertedIds },
80
+ });
81
+ return {
82
+ records: docs.map(d => (0, mapping_js_1.mapDocumentToGraphql)(d, nestedSelection(selection, 'records'))),
83
+ recordIds: insertedIds.map(id => String(id)),
84
+ createdCount: insertedCount,
85
+ };
86
+ }
87
+ case 'UPDATE_ONE': {
88
+ const setDoc = (0, filter_js_1.buildSetDocument)(directive.set, ctx);
89
+ await client.updateOne(directive.collection, filter, { $set: setDoc });
90
+ const updated = await client.findOne(directive.collection, filter);
91
+ return mapPayload(updated, updated?._id, selection);
92
+ }
93
+ case 'UPDATE_MANY': {
94
+ const setDoc = (0, filter_js_1.buildSetDocument)(directive.set, ctx);
95
+ const result = await client.updateMany(directive.collection, filter, { $set: setDoc });
96
+ return {
97
+ matchedCount: result.matchedCount,
98
+ modifiedCount: result.modifiedCount,
99
+ };
100
+ }
101
+ case 'DELETE_ONE': {
102
+ const existing = await client.findOne(directive.collection, filter);
103
+ await client.deleteOne(directive.collection, filter);
104
+ return mapPayload(existing, existing?._id, selection);
105
+ }
106
+ case 'DELETE_MANY': {
107
+ const result = await client.deleteMany(directive.collection, filter);
108
+ return { deletedCount: result.deletedCount };
109
+ }
110
+ case 'AGGREGATE': {
111
+ const pipeline = resolvePipeline(directive.pipeline, ctx, filter);
112
+ const rows = await client.aggregate(directive.collection, pipeline);
113
+ return rows.map(doc => (0, mapping_js_1.mapDocumentToGraphql)(doc, selection));
114
+ }
115
+ default:
116
+ throw new Error(`@mongo kind ${directive.kind} is not implemented`);
117
+ }
118
+ };
119
+ return fieldConfig;
120
+ }
121
+ async function resolveConnection(client, directive, filter, sort, projection, ctx, selection) {
122
+ const first = resolveBinderNumber(directive.first, ctx) ?? 10;
123
+ const after = resolveBinderString(directive.after, ctx);
124
+ const connFilter = { ...filter };
125
+ if (after) {
126
+ connFilter._id = {
127
+ ...(typeof connFilter._id === 'object' && connFilter._id ? connFilter._id : {}),
128
+ $gt: (0, filter_js_1.coerceFilterValue)(after),
129
+ };
130
+ }
131
+ const docs = await client.findMany(directive.collection, connFilter, {
132
+ projection,
133
+ sort: sort || { _id: 1 },
134
+ limit: first + 1,
135
+ });
136
+ const hasNextPage = docs.length > first;
137
+ const pageDocs = hasNextPage ? docs.slice(0, first) : docs;
138
+ const totalCount = await client.count(directive.collection, filter);
139
+ const nodesSel = nestedSelection(selection, 'nodes');
140
+ const nodes = pageDocs.map(d => (0, mapping_js_1.mapDocumentToGraphql)(d, nodesSel));
141
+ const edges = pageDocs.map(d => ({
142
+ cursor: String(d._id),
143
+ node: (0, mapping_js_1.mapDocumentToGraphql)(d, nestedSelection(nestedSelection(selection, 'edges'), 'node')),
144
+ }));
145
+ return {
146
+ nodes,
147
+ edges,
148
+ pageInfo: {
149
+ hasNextPage,
150
+ hasPreviousPage: Boolean(after),
151
+ startCursor: edges[0]?.cursor ?? null,
152
+ endCursor: edges[edges.length - 1]?.cursor ?? null,
153
+ },
154
+ totalCount,
155
+ };
156
+ }
157
+ async function resolvePagination(client, directive, filter, sort, projection, ctx, selection) {
158
+ const page = Math.max(1, resolveBinderNumber(directive.page, ctx) ?? 1);
159
+ const perPage = Math.max(1, resolveBinderNumber(directive.perPage, ctx) ?? 20);
160
+ const itemCount = await client.count(directive.collection, filter);
161
+ const pageCount = Math.ceil(itemCount / perPage) || 0;
162
+ const docs = await client.findMany(directive.collection, filter, {
163
+ projection,
164
+ sort,
165
+ skip: (page - 1) * perPage,
166
+ limit: perPage,
167
+ });
168
+ const itemsSel = nestedSelection(selection, 'items');
169
+ return {
170
+ count: docs.length,
171
+ items: docs.map(d => (0, mapping_js_1.mapDocumentToGraphql)(d, itemsSel)),
172
+ pageInfo: {
173
+ currentPage: page,
174
+ perPage,
175
+ pageCount,
176
+ itemCount,
177
+ hasNextPage: page < pageCount,
178
+ hasPreviousPage: page > 1,
179
+ },
180
+ };
181
+ }
182
+ function mapPayload(doc, id, selection) {
183
+ const recordSel = nestedSelection(selection, 'record');
184
+ return {
185
+ record: (0, mapping_js_1.mapDocumentToGraphql)(doc, recordSel.entries.length ? recordSel : selection),
186
+ recordId: id != null ? String(id) : null,
187
+ };
188
+ }
189
+ function nestedSelection(selection, key) {
190
+ const entry = selection.entries.find(e => e.key === key);
191
+ return { entries: entry?.children || [] };
192
+ }
193
+ function resolvePipeline(pipelineSource, ctx, filter) {
194
+ if (!pipelineSource || !pipelineSource.trim()) {
195
+ return Object.keys(filter).length ? [{ $match: filter }] : [];
196
+ }
197
+ const trimmed = pipelineSource.trim();
198
+ if (trimmed.startsWith('[')) {
199
+ try {
200
+ const parsed = JSON.parse(trimmed);
201
+ return parsed.map(stage => {
202
+ if (stage.$match === '$args.filter' || stage.$match === '$filter') {
203
+ return { $match: filter };
204
+ }
205
+ return stage;
206
+ });
207
+ }
208
+ catch {
209
+ // fall through
210
+ }
211
+ }
212
+ // Mapping-style: treat as match binder only
213
+ const fromMapping = (0, filter_js_1.buildMongoFilter)(pipelineSource, ctx);
214
+ return Object.keys(fromMapping).length ? [{ $match: fromMapping }] : [{ $match: filter }];
215
+ }
216
+ function resolveBinderNumber(source, ctx) {
217
+ if (!source)
218
+ return undefined;
219
+ const parsed = (0, mapping_js_1.parseMongoMapping)(source);
220
+ if (parsed.entries.length === 1 && parsed.entries[0].value) {
221
+ const val = (0, mapping_js_1.resolveMappingValue)(parsed.entries[0].value, ctx);
222
+ if (typeof val === 'number')
223
+ return val;
224
+ if (typeof val === 'string' && val.trim() !== '')
225
+ return Number(val);
226
+ }
227
+ return undefined;
228
+ }
229
+ function resolveBinderString(source, ctx) {
230
+ if (!source)
231
+ return undefined;
232
+ const parsed = (0, mapping_js_1.parseMongoMapping)(source);
233
+ if (parsed.entries.length === 1 && parsed.entries[0].value) {
234
+ const val = (0, mapping_js_1.resolveMappingValue)(parsed.entries[0].value, ctx);
235
+ if (typeof val === 'string')
236
+ return val;
237
+ }
238
+ return undefined;
239
+ }
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.graphqlWhereToMongo = void 0;
4
+ exports.buildMongoFilter = buildMongoFilter;
5
+ exports.filterFromMapping = filterFromMapping;
6
+ exports.graphqlFilterToMongo = graphqlFilterToMongo;
7
+ exports.buildMongoSort = buildMongoSort;
8
+ exports.graphqlSortToMongo = graphqlSortToMongo;
9
+ exports.buildSetDocument = buildSetDocument;
10
+ exports.coerceFilterValue = coerceFilterValue;
11
+ const mongodb_1 = require("mongodb");
12
+ const mapping_js_1 = require("./mapping.js");
13
+ /**
14
+ * Build a MongoDB filter document from `@mongo(filter:)` (or legacy `where:`) mapping.
15
+ */
16
+ function buildMongoFilter(filterSource, ctx) {
17
+ const parsed = (0, mapping_js_1.parseMongoMapping)(filterSource);
18
+ return filterFromMapping(parsed, ctx);
19
+ }
20
+ function filterFromMapping(parsed, ctx) {
21
+ const filter = {};
22
+ for (const entry of parsed.entries) {
23
+ if (entry.spread && entry.value) {
24
+ const spreadVal = (0, mapping_js_1.resolveMappingValue)(entry.value, ctx);
25
+ if (spreadVal && typeof spreadVal === 'object' && !Array.isArray(spreadVal)) {
26
+ Object.assign(filter, graphqlFilterToMongo(spreadVal));
27
+ }
28
+ continue;
29
+ }
30
+ // Bare `$args.filter` / `$args.where` binder
31
+ if (entry.value?.kind === 'args' &&
32
+ (entry.key.startsWith('$args') || entry.key === `$args.${entry.value.value}`)) {
33
+ const val = (0, mapping_js_1.resolveMappingValue)(entry.value, ctx);
34
+ if (val && typeof val === 'object' && !Array.isArray(val)) {
35
+ Object.assign(filter, graphqlFilterToMongo(val));
36
+ }
37
+ continue;
38
+ }
39
+ if (entry.children || !entry.value)
40
+ continue;
41
+ const resolved = (0, mapping_js_1.resolveMappingValue)(entry.value, ctx);
42
+ if (resolved === undefined)
43
+ continue;
44
+ // `_id: $args._ids` (array) => `{ _id: { $in: [...] } }`
45
+ if (Array.isArray(resolved)) {
46
+ filter[entry.key] = { $in: resolved.map(coerceFilterValue) };
47
+ }
48
+ else {
49
+ filter[entry.key] = coerceFilterValue(resolved);
50
+ }
51
+ }
52
+ return filter;
53
+ }
54
+ /** @deprecated alias */
55
+ exports.graphqlWhereToMongo = graphqlFilterToMongo;
56
+ function graphqlFilterToMongo(input) {
57
+ const out = {};
58
+ for (const [key, value] of Object.entries(input)) {
59
+ if (value == null)
60
+ continue;
61
+ if (key === 'AND' || key === 'and') {
62
+ out.$and = value.map(graphqlFilterToMongo);
63
+ continue;
64
+ }
65
+ if (key === 'OR' || key === 'or') {
66
+ out.$or = value.map(graphqlFilterToMongo);
67
+ continue;
68
+ }
69
+ if (key === 'NOT' || key === 'not') {
70
+ out.$nor = [graphqlFilterToMongo(value)];
71
+ continue;
72
+ }
73
+ const mongoKey = key === 'id' ? '_id' : key;
74
+ if (typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {
75
+ out[mongoKey] = coerceFilterValue(value);
76
+ continue;
77
+ }
78
+ const ops = value;
79
+ const mongoOps = {};
80
+ let hasOps = false;
81
+ for (const [op, opVal] of Object.entries(ops)) {
82
+ if (opVal === undefined)
83
+ continue;
84
+ hasOps = true;
85
+ switch (op) {
86
+ case 'eq':
87
+ out[mongoKey] = coerceFilterValue(opVal);
88
+ hasOps = false;
89
+ break;
90
+ case 'ne':
91
+ mongoOps.$ne = coerceFilterValue(opVal);
92
+ break;
93
+ case 'in':
94
+ mongoOps.$in = opVal.map(coerceFilterValue);
95
+ break;
96
+ case 'nin':
97
+ mongoOps.$nin = opVal.map(coerceFilterValue);
98
+ break;
99
+ case 'gt':
100
+ mongoOps.$gt = coerceFilterValue(opVal);
101
+ break;
102
+ case 'gte':
103
+ mongoOps.$gte = coerceFilterValue(opVal);
104
+ break;
105
+ case 'lt':
106
+ mongoOps.$lt = coerceFilterValue(opVal);
107
+ break;
108
+ case 'lte':
109
+ mongoOps.$lte = coerceFilterValue(opVal);
110
+ break;
111
+ case 'regex':
112
+ mongoOps.$regex = opVal;
113
+ break;
114
+ case 'exists':
115
+ mongoOps.$exists = opVal;
116
+ break;
117
+ default:
118
+ break;
119
+ }
120
+ if (!hasOps && op === 'eq')
121
+ break;
122
+ }
123
+ if (hasOps && Object.keys(mongoOps).length) {
124
+ out[mongoKey] = mongoOps;
125
+ }
126
+ }
127
+ return out;
128
+ }
129
+ function buildMongoSort(sortSource, ctx) {
130
+ if (!sortSource)
131
+ return undefined;
132
+ const parsed = (0, mapping_js_1.parseMongoMapping)(sortSource);
133
+ if (parsed.entries.length === 1 && parsed.entries[0].value?.kind === 'args') {
134
+ const val = (0, mapping_js_1.resolveMappingValue)(parsed.entries[0].value, ctx);
135
+ return graphqlSortToMongo(val);
136
+ }
137
+ return undefined;
138
+ }
139
+ function graphqlSortToMongo(input) {
140
+ if (!input || typeof input !== 'object')
141
+ return undefined;
142
+ const out = {};
143
+ for (const [key, dir] of Object.entries(input)) {
144
+ if (dir == null)
145
+ continue;
146
+ const mongoKey = key === 'id' ? '_id' : key;
147
+ const d = String(dir).toUpperCase();
148
+ out[mongoKey] = d === 'DESC' || d === '-1' ? -1 : 1;
149
+ }
150
+ return Object.keys(out).length ? out : undefined;
151
+ }
152
+ function buildSetDocument(setSource, ctx) {
153
+ const parsed = (0, mapping_js_1.parseMongoMapping)(setSource);
154
+ const doc = {};
155
+ for (const entry of parsed.entries) {
156
+ if (entry.key === 'records' && entry.value?.kind === 'args') {
157
+ continue;
158
+ }
159
+ if (!entry.value)
160
+ continue;
161
+ const resolved = (0, mapping_js_1.resolveMappingValue)(entry.value, ctx);
162
+ if (resolved === undefined)
163
+ continue;
164
+ doc[entry.key] = resolved;
165
+ }
166
+ return doc;
167
+ }
168
+ function coerceFilterValue(value) {
169
+ if (typeof value === 'string' && mongodb_1.ObjectId.isValid(value) && value.length === 24) {
170
+ try {
171
+ return new mongodb_1.ObjectId(value);
172
+ }
173
+ catch {
174
+ return value;
175
+ }
176
+ }
177
+ return value;
178
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const execution_js_1 = require("./execution.js");
5
+ tslib_1.__exportStar(require("./client.js"), exports);
6
+ tslib_1.__exportStar(require("./execution.js"), exports);
7
+ tslib_1.__exportStar(require("./filter.js"), exports);
8
+ tslib_1.__exportStar(require("./mapping.js"), exports);
9
+ exports.default = {
10
+ getSubgraphExecutor({ subgraph, cwd }) {
11
+ return (0, execution_js_1.getMongoExecutor)({
12
+ subgraph,
13
+ cwd,
14
+ });
15
+ },
16
+ };