@omnigraph/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/src/schema.ts ADDED
@@ -0,0 +1,886 @@
1
+ import {
2
+ GraphQLFloat,
3
+ GraphQLID,
4
+ GraphQLInt,
5
+ GraphQLList,
6
+ GraphQLNonNull,
7
+ GraphQLObjectType,
8
+ GraphQLString,
9
+ type GraphQLSchema,
10
+ } from 'graphql';
11
+ import { SchemaComposer } from 'graphql-compose';
12
+ import { GraphQLDateTime, GraphQLJSON, GraphQLObjectID } from 'graphql-scalars';
13
+ import type { Model, Schema as MongooseSchema } from 'mongoose';
14
+ import { process as meshProcess } from '@graphql-mesh/cross-helpers';
15
+ import type { ImportFn } from '@graphql-mesh/types';
16
+ import { defaultImportFn, loadFromModuleExportExpression } from '@graphql-mesh/utils';
17
+ import { MongoDirective, MongoKindEnum, TransportDirective } from './directives.js';
18
+ import { createDefaultNaming, type MongoNaming } from './naming.js';
19
+ import { mapMongoPathToGraphQL } from './type-map.js';
20
+
21
+ const FEDERATION_LINK_URL = 'https://specs.apollo.dev/federation/v2.6';
22
+
23
+ export interface MongoModelConfig {
24
+ name: string;
25
+ path?: string;
26
+ model?: Model<any>;
27
+ schema?: MongooseSchema;
28
+ collection?: string;
29
+ }
30
+
31
+ export interface LoadMongoSubgraphOpts {
32
+ endpoint: string;
33
+ models: MongoModelConfig[];
34
+ cwd?: string;
35
+ naming?: Partial<MongoNaming>;
36
+ importFn?: ImportFn;
37
+ }
38
+
39
+ export async function loadGraphQLSchemaFromMongo(
40
+ subgraphName: string,
41
+ opts: LoadMongoSubgraphOpts,
42
+ ): Promise<GraphQLSchema> {
43
+ const naming: MongoNaming = { ...createDefaultNaming(), ...opts.naming };
44
+ const cwd = opts.cwd || meshProcess.cwd();
45
+ const importFn = opts.importFn || defaultImportFn;
46
+ const schemaComposer = new SchemaComposer();
47
+
48
+ schemaComposer.add(GraphQLObjectID);
49
+ schemaComposer.add(GraphQLDateTime);
50
+ schemaComposer.add(GraphQLJSON);
51
+ schemaComposer.addDirective(TransportDirective);
52
+ schemaComposer.addDirective(MongoDirective);
53
+ schemaComposer.add(MongoKindEnum);
54
+
55
+ ensureSharedFilterInputs(schemaComposer);
56
+ ensurePageInfo(schemaComposer);
57
+
58
+ const modelMeta: Array<{
59
+ typeName: string;
60
+ collection: string;
61
+ schema: MongooseSchema;
62
+ paths: PathMeta[];
63
+ }> = [];
64
+
65
+ for (const modelConfig of opts.models) {
66
+ const model = await resolveModel(modelConfig, cwd, importFn);
67
+ const collection =
68
+ modelConfig.collection ||
69
+ (model as any).collection?.collectionName ||
70
+ model.schema?.get('collection') ||
71
+ pluralizeFallback(modelConfig.name);
72
+ const typeName = naming.typeName(modelConfig.name);
73
+ const paths = introspectPaths(model.schema);
74
+ modelMeta.push({ typeName, collection, schema: model.schema, paths });
75
+ emitModelObjectType(schemaComposer, {
76
+ subgraphName,
77
+ typeName,
78
+ collection,
79
+ paths,
80
+ naming,
81
+ });
82
+ }
83
+
84
+ for (const meta of modelMeta) {
85
+ emitModelRootFields(schemaComposer, {
86
+ subgraphName,
87
+ typeName: meta.typeName,
88
+ collection: meta.collection,
89
+ paths: meta.paths,
90
+ naming,
91
+ });
92
+ emitRefFields(schemaComposer, {
93
+ subgraphName,
94
+ typeName: meta.typeName,
95
+ schema: meta.schema,
96
+ naming,
97
+ knownTypes: new Set(modelMeta.map(m => m.typeName)),
98
+ collectionsByType: new Map(modelMeta.map(m => [m.typeName, m.collection])),
99
+ });
100
+ }
101
+
102
+ const schema = schemaComposer.buildSchema();
103
+ const extensions: Record<string, any> = (schema.extensions ||= {});
104
+ extensions.directives ||= {};
105
+ extensions.directives.transport = {
106
+ subgraph: subgraphName,
107
+ kind: 'mongo',
108
+ location: opts.endpoint,
109
+ };
110
+ extensions.directives.link = [
111
+ {
112
+ url: FEDERATION_LINK_URL,
113
+ import: ['@key'],
114
+ },
115
+ ];
116
+ markMongoDirectiveStringsAsBlocks(schema);
117
+ return schema;
118
+ }
119
+
120
+ async function resolveModel(
121
+ config: MongoModelConfig,
122
+ cwd: string,
123
+ importFn: ImportFn,
124
+ ): Promise<Model<any>> {
125
+ if (config.model) return config.model;
126
+ if (config.schema) {
127
+ return {
128
+ schema: config.schema,
129
+ collection: { collectionName: config.collection || pluralizeFallback(config.name) },
130
+ } as any;
131
+ }
132
+ if (!config.path) {
133
+ throw new Error(`Model ${config.name} needs path, model, or schema`);
134
+ }
135
+ const model = await loadFromModuleExportExpression<Model<any>>(config.path, {
136
+ defaultExportName: config.name,
137
+ cwd,
138
+ importFn,
139
+ });
140
+ if (!model) {
141
+ throw new Error(`Model ${config.name} cannot be imported from ${config.path}`);
142
+ }
143
+ return model;
144
+ }
145
+
146
+ interface PathMeta {
147
+ name: string;
148
+ instance: string;
149
+ isArray?: boolean;
150
+ enumValues?: string[];
151
+ ref?: string;
152
+ }
153
+
154
+ function introspectPaths(schema: MongooseSchema): PathMeta[] {
155
+ const out: PathMeta[] = [];
156
+ const paths = (schema as any).paths || {};
157
+ for (const [name, schemaType] of Object.entries(paths) as [string, any][]) {
158
+ const instance = schemaType.instance || schemaType.constructor?.name || 'Mixed';
159
+ const enumValues = schemaType.enumValues || schemaType.options?.enum;
160
+ const ref =
161
+ schemaType.options?.ref ||
162
+ schemaType.caster?.options?.ref ||
163
+ schemaType.schema?.options?.ref;
164
+ out.push({
165
+ name,
166
+ instance: String(instance),
167
+ isArray: instance === 'Array' || Array.isArray(schemaType.options?.type),
168
+ enumValues: Array.isArray(enumValues) ? enumValues.map(String) : undefined,
169
+ ref: ref ? String(ref) : undefined,
170
+ });
171
+ }
172
+ return out;
173
+ }
174
+
175
+ function selectionForPaths(paths: PathMeta[]): string {
176
+ const lines = ['id: _id'];
177
+ for (const path of paths) {
178
+ if (path.name === '_id' || path.name === '__v' || path.name.includes('.')) continue;
179
+ if (path.ref) {
180
+ // Scalar id field kept; populated object is a sibling field.
181
+ lines.push(`${path.name}: ${path.name}`);
182
+ continue;
183
+ }
184
+ lines.push(`${path.name}: ${path.name}`);
185
+ }
186
+ return blockArg(lines.join('\n'));
187
+ }
188
+
189
+ function emitModelObjectType(
190
+ schemaComposer: SchemaComposer,
191
+ opts: {
192
+ subgraphName: string;
193
+ typeName: string;
194
+ collection: string;
195
+ paths: PathMeta[];
196
+ naming: MongoNaming;
197
+ },
198
+ ) {
199
+ const { subgraphName, typeName, collection, paths, naming } = opts;
200
+ const otc = schemaComposer.createObjectTC({ name: typeName, fields: {} });
201
+ const selection = selectionForPaths(paths);
202
+
203
+ otc.setField('id', { type: new GraphQLNonNull(GraphQLID) });
204
+ for (const path of paths) {
205
+ if (path.name === '_id' || path.name === '__v' || path.name.includes('.')) continue;
206
+ otc.setField(path.name, { type: mapPathToOutput(path) });
207
+ }
208
+
209
+ otc.setDirectives([
210
+ { name: 'key', args: { fields: 'id' } },
211
+ {
212
+ name: 'mongo',
213
+ args: {
214
+ subgraph: subgraphName,
215
+ collection,
216
+ kind: 'FIND_ONE',
217
+ filter: blockArg('_id: $this.id'),
218
+ selection,
219
+ },
220
+ },
221
+ ]);
222
+
223
+ createFilterSortAndInputs(schemaComposer, naming, typeName, paths);
224
+ createConnectionTypes(schemaComposer, naming, typeName);
225
+ createPayloadType(schemaComposer, naming, typeName);
226
+ }
227
+
228
+ function emitModelRootFields(
229
+ schemaComposer: SchemaComposer,
230
+ opts: {
231
+ subgraphName: string;
232
+ typeName: string;
233
+ collection: string;
234
+ paths: PathMeta[];
235
+ naming: MongoNaming;
236
+ },
237
+ ) {
238
+ const { subgraphName, typeName, collection, paths, naming } = opts;
239
+ const selection = selectionForPaths(paths);
240
+ const filterType = naming.filterInput(typeName);
241
+ const sortType = naming.sortInput(typeName);
242
+ const queryTC = schemaComposer.Query;
243
+ const mutationTC = schemaComposer.Mutation;
244
+
245
+ const mongo = (
246
+ kind: string,
247
+ extra: Record<string, unknown> = {},
248
+ ): { name: string; args: Record<string, unknown> } => ({
249
+ name: 'mongo',
250
+ args: { subgraph: subgraphName, collection, kind, selection, ...extra },
251
+ });
252
+
253
+ queryTC.setField(naming.findByIdField(typeName), {
254
+ type: typeName,
255
+ args: { _id: { type: new GraphQLNonNull(GraphQLID) } },
256
+ directives: [mongo('FIND_ONE', { filter: blockArg('_id: $args._id') })],
257
+ });
258
+
259
+ queryTC.setField(naming.dataLoaderField(typeName), {
260
+ type: typeName,
261
+ args: { _id: { type: new GraphQLNonNull(GraphQLID) } },
262
+ directives: [mongo('FIND_ONE', { filter: blockArg('_id: $args._id') })],
263
+ });
264
+
265
+ queryTC.setField(naming.findByIdsField(typeName), {
266
+ type: `[${typeName}!]!`,
267
+ args: {
268
+ _ids: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))) },
269
+ limit: { type: GraphQLInt, defaultValue: 100 },
270
+ sort: { type: sortType },
271
+ },
272
+ directives: [
273
+ mongo('FIND_MANY', {
274
+ filter: blockArg('_id: $args._ids'),
275
+ limit: '$args.limit',
276
+ sort: '$args.sort',
277
+ }),
278
+ ],
279
+ });
280
+
281
+ queryTC.setField(naming.dataLoaderManyField(typeName), {
282
+ type: `[${typeName}]!`,
283
+ args: {
284
+ _ids: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))) },
285
+ },
286
+ directives: [mongo('FIND_MANY', { filter: blockArg('_id: $args._ids') })],
287
+ });
288
+
289
+ queryTC.setField(naming.findManyField(typeName), {
290
+ type: `[${typeName}!]!`,
291
+ args: {
292
+ filter: { type: filterType },
293
+ limit: { type: GraphQLInt, defaultValue: 100 },
294
+ skip: { type: GraphQLInt },
295
+ sort: { type: sortType },
296
+ },
297
+ directives: [
298
+ mongo('FIND_MANY', {
299
+ filter: '$args.filter',
300
+ sort: '$args.sort',
301
+ limit: '$args.limit',
302
+ skip: '$args.skip',
303
+ }),
304
+ ],
305
+ });
306
+
307
+ queryTC.setField(naming.findOneField(typeName), {
308
+ type: typeName,
309
+ args: {
310
+ filter: { type: filterType },
311
+ skip: { type: GraphQLInt },
312
+ sort: { type: sortType },
313
+ },
314
+ directives: [
315
+ mongo('FIND_ONE', {
316
+ filter: '$args.filter',
317
+ sort: '$args.sort',
318
+ skip: '$args.skip',
319
+ }),
320
+ ],
321
+ });
322
+
323
+ queryTC.setField(naming.countField(typeName), {
324
+ type: new GraphQLNonNull(GraphQLInt),
325
+ args: { filter: { type: filterType } },
326
+ directives: [mongo('COUNT', { filter: '$args.filter', selection: blockArg('$') })],
327
+ });
328
+
329
+ queryTC.setField(naming.connectionField(typeName), {
330
+ type: naming.connectionType(typeName),
331
+ args: {
332
+ filter: { type: filterType },
333
+ first: { type: GraphQLInt },
334
+ after: { type: GraphQLString },
335
+ sort: { type: sortType },
336
+ },
337
+ directives: [
338
+ mongo('CONNECTION', {
339
+ filter: '$args.filter',
340
+ sort: '$args.sort',
341
+ first: '$args.first',
342
+ after: '$args.after',
343
+ selection: blockArg(`
344
+ nodes {
345
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
346
+ }
347
+ edges {
348
+ cursor: $cursor
349
+ node {
350
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 2)}
351
+ }
352
+ }
353
+ pageInfo {
354
+ hasNextPage: $hasNextPage
355
+ hasPreviousPage: $hasPreviousPage
356
+ startCursor: $startCursor
357
+ endCursor: $endCursor
358
+ }
359
+ totalCount: $totalCount
360
+ `),
361
+ }),
362
+ ],
363
+ });
364
+
365
+ queryTC.setField(naming.paginationField(typeName), {
366
+ type: naming.paginationType(typeName),
367
+ args: {
368
+ filter: { type: filterType },
369
+ page: { type: GraphQLInt },
370
+ perPage: { type: GraphQLInt, defaultValue: 20 },
371
+ sort: { type: sortType },
372
+ },
373
+ directives: [
374
+ mongo('PAGINATION', {
375
+ filter: '$args.filter',
376
+ sort: '$args.sort',
377
+ page: '$args.page',
378
+ perPage: '$args.perPage',
379
+ selection: blockArg(`
380
+ count: $count
381
+ items {
382
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
383
+ }
384
+ pageInfo {
385
+ currentPage: $currentPage
386
+ perPage: $perPage
387
+ pageCount: $pageCount
388
+ itemCount: $itemCount
389
+ hasNextPage: $hasNextPage
390
+ hasPreviousPage: $hasPreviousPage
391
+ }
392
+ `),
393
+ }),
394
+ ],
395
+ });
396
+
397
+ const setBlock = blockArg(
398
+ paths
399
+ .filter(p => p.name !== '_id' && p.name !== '__v' && !p.name.includes('.'))
400
+ .map(p => `${p.name}: $args.record.${p.name}`)
401
+ .join('\n'),
402
+ );
403
+ const payloadSelection = blockArg(`
404
+ record {
405
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
406
+ }
407
+ recordId: $_id
408
+ `);
409
+
410
+ mutationTC.setField(naming.createOneField(typeName), {
411
+ type: naming.payloadType(typeName),
412
+ args: { record: { type: `${naming.createInput(typeName)}!` } },
413
+ directives: [mongo('INSERT_ONE', { set: setBlock, selection: payloadSelection })],
414
+ });
415
+
416
+ mutationTC.setField(naming.createManyField(typeName), {
417
+ type: naming.payloadType(typeName),
418
+ args: { records: { type: `[${naming.createInput(typeName)}!]!` } },
419
+ directives: [
420
+ mongo('INSERT_MANY', {
421
+ set: blockArg('records: $args.records'),
422
+ selection: blockArg(`
423
+ records {
424
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
425
+ }
426
+ recordIds: $recordIds
427
+ createdCount: $createdCount
428
+ `),
429
+ }),
430
+ ],
431
+ });
432
+
433
+ mutationTC.setField(naming.updateByIdField(typeName), {
434
+ type: naming.payloadType(typeName),
435
+ args: {
436
+ _id: { type: new GraphQLNonNull(GraphQLID) },
437
+ record: { type: `${naming.updateInput(typeName)}!` },
438
+ },
439
+ directives: [
440
+ mongo('UPDATE_ONE', {
441
+ filter: blockArg('_id: $args._id'),
442
+ set: setBlock,
443
+ selection: payloadSelection,
444
+ }),
445
+ ],
446
+ });
447
+
448
+ mutationTC.setField(naming.updateOneField(typeName), {
449
+ type: naming.payloadType(typeName),
450
+ args: {
451
+ filter: { type: filterType },
452
+ record: { type: `${naming.updateInput(typeName)}!` },
453
+ },
454
+ directives: [
455
+ mongo('UPDATE_ONE', {
456
+ filter: '$args.filter',
457
+ set: setBlock,
458
+ selection: payloadSelection,
459
+ }),
460
+ ],
461
+ });
462
+
463
+ mutationTC.setField(naming.updateManyField(typeName), {
464
+ type: naming.payloadType(typeName),
465
+ args: {
466
+ filter: { type: filterType },
467
+ record: { type: `${naming.updateInput(typeName)}!` },
468
+ },
469
+ directives: [
470
+ mongo('UPDATE_MANY', {
471
+ filter: '$args.filter',
472
+ set: setBlock,
473
+ selection: blockArg(`
474
+ modifiedCount: $modifiedCount
475
+ matchedCount: $matchedCount
476
+ `),
477
+ }),
478
+ ],
479
+ });
480
+
481
+ mutationTC.setField(naming.removeByIdField(typeName), {
482
+ type: naming.payloadType(typeName),
483
+ args: { _id: { type: new GraphQLNonNull(GraphQLID) } },
484
+ directives: [
485
+ mongo('DELETE_ONE', {
486
+ filter: blockArg('_id: $args._id'),
487
+ selection: payloadSelection,
488
+ }),
489
+ ],
490
+ });
491
+
492
+ mutationTC.setField(naming.removeOneField(typeName), {
493
+ type: naming.payloadType(typeName),
494
+ args: { filter: { type: filterType } },
495
+ directives: [
496
+ mongo('DELETE_ONE', {
497
+ filter: '$args.filter',
498
+ selection: payloadSelection,
499
+ }),
500
+ ],
501
+ });
502
+
503
+ mutationTC.setField(naming.removeManyField(typeName), {
504
+ type: naming.payloadType(typeName),
505
+ args: { filter: { type: `${filterType}!` } },
506
+ directives: [
507
+ mongo('DELETE_MANY', {
508
+ filter: '$args.filter',
509
+ selection: blockArg('deletedCount: $deletedCount'),
510
+ }),
511
+ ],
512
+ });
513
+ }
514
+
515
+ function emitRefFields(
516
+ schemaComposer: SchemaComposer,
517
+ opts: {
518
+ subgraphName: string;
519
+ typeName: string;
520
+ schema: MongooseSchema;
521
+ naming: MongoNaming;
522
+ knownTypes: Set<string>;
523
+ collectionsByType: Map<string, string>;
524
+ },
525
+ ) {
526
+ const paths = introspectPaths(opts.schema);
527
+ const otc = schemaComposer.getOTC(opts.typeName);
528
+ for (const path of paths) {
529
+ if (!path.ref || !opts.knownTypes.has(path.ref)) continue;
530
+ const refCollection = opts.collectionsByType.get(path.ref);
531
+ if (!refCollection) continue;
532
+ const refPaths = introspectPaths(
533
+ // best-effort: empty selection of id only if we cannot re-introspect
534
+ opts.schema,
535
+ );
536
+ void refPaths;
537
+ const fieldName = path.isArray ? pluralizeFallback(path.ref) : path.ref[0].toLowerCase() + path.ref.slice(1);
538
+ // Prefer path name without Id suffix when present (authorId -> author)
539
+ const pretty =
540
+ path.name.endsWith('Id') || path.name.endsWith('Ids')
541
+ ? path.name.replace(/Ids?$/, '')
542
+ : path.name + 'Doc';
543
+ const finalName = otc.hasField(pretty) ? fieldName : pretty;
544
+ if (otc.hasField(finalName) && finalName !== path.name) {
545
+ // already set
546
+ }
547
+ const refSelection = blockArg('id: _id');
548
+ if (path.isArray) {
549
+ otc.setField(finalName, {
550
+ type: `[${path.ref}!]!`,
551
+ directives: [
552
+ {
553
+ name: 'mongo',
554
+ args: {
555
+ subgraph: opts.subgraphName,
556
+ collection: refCollection,
557
+ kind: 'FIND_MANY',
558
+ filter: blockArg(`_id: $this.${path.name}`),
559
+ selection: refSelection,
560
+ },
561
+ },
562
+ ],
563
+ });
564
+ } else {
565
+ otc.setField(finalName, {
566
+ type: path.ref,
567
+ directives: [
568
+ {
569
+ name: 'mongo',
570
+ args: {
571
+ subgraph: opts.subgraphName,
572
+ collection: refCollection,
573
+ kind: 'FIND_ONE',
574
+ filter: blockArg(`_id: $this.${path.name}`),
575
+ selection: refSelection,
576
+ },
577
+ },
578
+ ],
579
+ });
580
+ }
581
+ }
582
+ }
583
+
584
+ function mapPathToOutput(path: PathMeta) {
585
+ if (path.enumValues?.length) {
586
+ return path.isArray ? new GraphQLList(GraphQLString) : GraphQLString;
587
+ }
588
+ if (path.ref) {
589
+ const idType = GraphQLID;
590
+ return path.isArray ? new GraphQLList(idType) : idType;
591
+ }
592
+ if (path.isArray && path.instance !== 'Array') {
593
+ return new GraphQLList(mapMongoPathToGraphQL(path.instance));
594
+ }
595
+ return mapMongoPathToGraphQL(path.instance, { asId: path.name === '_id' });
596
+ }
597
+
598
+ function createFilterSortAndInputs(
599
+ schemaComposer: SchemaComposer,
600
+ naming: MongoNaming,
601
+ typeName: string,
602
+ paths: PathMeta[],
603
+ ) {
604
+ const filterName = naming.filterInput(typeName);
605
+ if (!schemaComposer.has(filterName)) {
606
+ schemaComposer.createInputTC({
607
+ name: filterName,
608
+ fields: {
609
+ AND: { type: `[${filterName}!]` },
610
+ OR: { type: `[${filterName}!]` },
611
+ NOT: { type: filterName },
612
+ id: { type: 'IDFilter' },
613
+ ...Object.fromEntries(
614
+ paths
615
+ .filter(p => p.name !== '_id' && p.name !== '__v' && !p.name.includes('.'))
616
+ .map(p => {
617
+ let filterType = 'StringFilter';
618
+ if (p.instance === 'Number' || p.instance === 'Decimal128') filterType = 'FloatFilter';
619
+ else if (p.instance === 'Boolean') filterType = 'BooleanFilter';
620
+ else if (p.instance === 'Date') filterType = 'DateTimeFilter';
621
+ else if (p.ref || p.instance === 'ObjectID' || p.instance === 'ObjectId')
622
+ filterType = 'IDFilter';
623
+ return [p.name, { type: filterType }];
624
+ }),
625
+ ),
626
+ },
627
+ });
628
+ }
629
+
630
+ if (!schemaComposer.has(naming.sortInput(typeName))) {
631
+ if (!schemaComposer.has('SortDirection')) {
632
+ schemaComposer.createEnumTC({
633
+ name: 'SortDirection',
634
+ values: { ASC: { value: 'ASC' }, DESC: { value: 'DESC' } },
635
+ });
636
+ }
637
+ schemaComposer.createInputTC({
638
+ name: naming.sortInput(typeName),
639
+ fields: {
640
+ id: 'SortDirection',
641
+ ...Object.fromEntries(
642
+ paths
643
+ .filter(p => p.name !== '_id' && p.name !== '__v' && !p.name.includes('.'))
644
+ .map(p => [p.name, { type: 'SortDirection' }]),
645
+ ),
646
+ },
647
+ });
648
+ }
649
+
650
+ const createFields: Record<string, any> = {};
651
+ const updateFields: Record<string, any> = {};
652
+ for (const path of paths) {
653
+ if (path.name === '_id' || path.name === '__v' || path.name.includes('.')) continue;
654
+ const gqlType = mapPathToOutput(path);
655
+ createFields[path.name] = { type: gqlType };
656
+ updateFields[path.name] = { type: gqlType };
657
+ }
658
+ if (!schemaComposer.has(naming.createInput(typeName))) {
659
+ schemaComposer.createInputTC({ name: naming.createInput(typeName), fields: createFields });
660
+ }
661
+ if (!schemaComposer.has(naming.updateInput(typeName))) {
662
+ schemaComposer.createInputTC({ name: naming.updateInput(typeName), fields: updateFields });
663
+ }
664
+ }
665
+
666
+ function createConnectionTypes(schemaComposer: SchemaComposer, naming: MongoNaming, typeName: string) {
667
+ if (!schemaComposer.has(naming.edgeType(typeName))) {
668
+ schemaComposer.createObjectTC({
669
+ name: naming.edgeType(typeName),
670
+ fields: { cursor: 'String!', node: `${typeName}!` },
671
+ });
672
+ }
673
+ if (!schemaComposer.has(naming.connectionType(typeName))) {
674
+ schemaComposer.createObjectTC({
675
+ name: naming.connectionType(typeName),
676
+ fields: {
677
+ edges: `[${naming.edgeType(typeName)}!]!`,
678
+ nodes: `[${typeName}!]!`,
679
+ pageInfo: 'PageInfo!',
680
+ totalCount: 'Int!',
681
+ },
682
+ });
683
+ }
684
+ if (!schemaComposer.has(naming.paginationType(typeName))) {
685
+ schemaComposer.createObjectTC({
686
+ name: naming.paginationType(typeName),
687
+ fields: {
688
+ count: 'Int',
689
+ items: `[${typeName}]`,
690
+ pageInfo: 'PaginationInfo',
691
+ },
692
+ });
693
+ }
694
+ }
695
+
696
+ function createPayloadType(schemaComposer: SchemaComposer, naming: MongoNaming, typeName: string) {
697
+ if (!schemaComposer.has(naming.payloadType(typeName))) {
698
+ schemaComposer.createObjectTC({
699
+ name: naming.payloadType(typeName),
700
+ fields: {
701
+ record: typeName,
702
+ recordId: GraphQLID,
703
+ records: `[${typeName}!]`,
704
+ recordIds: '[ID!]',
705
+ createdCount: GraphQLInt,
706
+ modifiedCount: GraphQLInt,
707
+ matchedCount: GraphQLInt,
708
+ deletedCount: GraphQLInt,
709
+ },
710
+ });
711
+ }
712
+ }
713
+
714
+ function ensurePageInfo(schemaComposer: SchemaComposer) {
715
+ if (!schemaComposer.has('PageInfo')) {
716
+ schemaComposer.createObjectTC({
717
+ name: 'PageInfo',
718
+ fields: {
719
+ hasNextPage: 'Boolean!',
720
+ hasPreviousPage: 'Boolean!',
721
+ startCursor: 'String',
722
+ endCursor: 'String',
723
+ },
724
+ });
725
+ }
726
+ if (!schemaComposer.has('PaginationInfo')) {
727
+ schemaComposer.createObjectTC({
728
+ name: 'PaginationInfo',
729
+ fields: {
730
+ currentPage: 'Int!',
731
+ perPage: 'Int!',
732
+ pageCount: 'Int',
733
+ itemCount: 'Int',
734
+ hasNextPage: 'Boolean',
735
+ hasPreviousPage: 'Boolean',
736
+ },
737
+ });
738
+ }
739
+ }
740
+
741
+ function ensureSharedFilterInputs(schemaComposer: SchemaComposer) {
742
+ if (!schemaComposer.has('IDFilter')) {
743
+ schemaComposer.createInputTC({
744
+ name: 'IDFilter',
745
+ fields: {
746
+ eq: GraphQLID,
747
+ ne: GraphQLID,
748
+ in: { type: new GraphQLList(new GraphQLNonNull(GraphQLID)) },
749
+ nin: { type: new GraphQLList(new GraphQLNonNull(GraphQLID)) },
750
+ exists: 'Boolean',
751
+ },
752
+ });
753
+ }
754
+ if (!schemaComposer.has('StringFilter')) {
755
+ schemaComposer.createInputTC({
756
+ name: 'StringFilter',
757
+ fields: {
758
+ eq: GraphQLString,
759
+ ne: GraphQLString,
760
+ in: { type: '[String!]' },
761
+ nin: { type: '[String!]' },
762
+ regex: GraphQLString,
763
+ exists: 'Boolean',
764
+ },
765
+ });
766
+ }
767
+ if (!schemaComposer.has('FloatFilter')) {
768
+ schemaComposer.createInputTC({
769
+ name: 'FloatFilter',
770
+ fields: {
771
+ eq: GraphQLFloat,
772
+ ne: GraphQLFloat,
773
+ in: { type: '[Float!]' },
774
+ nin: { type: '[Float!]' },
775
+ gt: GraphQLFloat,
776
+ gte: GraphQLFloat,
777
+ lt: GraphQLFloat,
778
+ lte: GraphQLFloat,
779
+ exists: 'Boolean',
780
+ },
781
+ });
782
+ }
783
+ if (!schemaComposer.has('BooleanFilter')) {
784
+ schemaComposer.createInputTC({
785
+ name: 'BooleanFilter',
786
+ fields: { eq: 'Boolean', ne: 'Boolean', exists: 'Boolean' },
787
+ });
788
+ }
789
+ if (!schemaComposer.has('DateTimeFilter')) {
790
+ schemaComposer.createInputTC({
791
+ name: 'DateTimeFilter',
792
+ fields: {
793
+ eq: 'DateTime',
794
+ ne: 'DateTime',
795
+ in: { type: '[DateTime!]' },
796
+ nin: { type: '[DateTime!]' },
797
+ gt: 'DateTime',
798
+ gte: 'DateTime',
799
+ lt: 'DateTime',
800
+ lte: 'DateTime',
801
+ exists: 'Boolean',
802
+ },
803
+ });
804
+ }
805
+ }
806
+
807
+ function markMongoDirectiveStringsAsBlocks(schema: GraphQLSchema): void {
808
+ const markNode = (astNode: { directives?: readonly any[] } | null | undefined) => {
809
+ const directives = astNode?.directives;
810
+ if (!directives) return;
811
+ for (const directive of directives) {
812
+ if (directive.name.value !== 'mongo' || !directive.arguments) continue;
813
+ for (const arg of directive.arguments) {
814
+ if (arg.value.kind !== 'StringValue') continue;
815
+ if (
816
+ arg.name.value !== 'filter' &&
817
+ arg.name.value !== 'where' &&
818
+ arg.name.value !== 'set' &&
819
+ arg.name.value !== 'selection' &&
820
+ arg.name.value !== 'pipeline'
821
+ ) {
822
+ continue;
823
+ }
824
+ if (isBareBinder(arg.value.value)) continue;
825
+ (arg.value as { block?: boolean }).block = true;
826
+ }
827
+ }
828
+ };
829
+ for (const type of Object.values(schema.getTypeMap())) {
830
+ if (!(type instanceof GraphQLObjectType)) continue;
831
+ markNode(type.astNode);
832
+ for (const field of Object.values(type.getFields())) {
833
+ markNode(field.astNode);
834
+ }
835
+ }
836
+ }
837
+
838
+ function isBareBinder(value: string): boolean {
839
+ const trimmed = value.trim();
840
+ if (
841
+ !trimmed.startsWith('$') ||
842
+ trimmed.includes('\n') ||
843
+ trimmed.includes(':') ||
844
+ trimmed.includes(' ')
845
+ ) {
846
+ return false;
847
+ }
848
+ if (trimmed.includes('...')) return false;
849
+ const segments = trimmed.slice(1).split('.');
850
+ if (!segments.length || segments.some(s => !s)) return false;
851
+ for (const seg of segments) {
852
+ const c0 = seg.charCodeAt(0);
853
+ const okStart = (c0 >= 65 && c0 <= 90) || (c0 >= 97 && c0 <= 122) || c0 === 95;
854
+ if (!okStart) return false;
855
+ for (let i = 1; i < seg.length; i++) {
856
+ const c = seg.charCodeAt(i);
857
+ const ok =
858
+ (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95;
859
+ if (!ok) return false;
860
+ }
861
+ }
862
+ return true;
863
+ }
864
+
865
+ function blockArg(body: string): string {
866
+ const trimmed = body.replace(/^\n+|\n+$/g, '');
867
+ const indented = trimmed
868
+ .split('\n')
869
+ .map(line => (line.length ? ` ${line}` : line))
870
+ .join('\n');
871
+ return indented.includes('\n') ? indented : `\n${indented}`;
872
+ }
873
+
874
+ function indent(body: string, levels: number): string {
875
+ const pad = ' '.repeat(levels);
876
+ return body
877
+ .split('\n')
878
+ .map(line => (line.length ? pad + line : line))
879
+ .join('\n');
880
+ }
881
+
882
+ function pluralizeFallback(name: string): string {
883
+ const lower = name.toLowerCase();
884
+ if (lower.endsWith('s')) return lower;
885
+ return `${lower}s`;
886
+ }