0
# Module Configuration
1
2
Core module configuration and setup for integrating GraphQL into NestJS applications. The GraphQLModule provides flexible configuration options supporting both synchronous and asynchronous patterns, multiple drivers, and extensive customization capabilities.
3
4
## Capabilities
5
6
### GraphQL Module
7
8
Main module class for integrating GraphQL into NestJS applications with static configuration methods.
9
10
```typescript { .api }
11
/**
12
* Main GraphQL module for NestJS integration
13
*/
14
export class GraphQLModule {
15
/**
16
* Configure GraphQL module synchronously
17
* @param options - Configuration options for GraphQL module
18
* @returns Dynamic module for NestJS
19
*/
20
static forRoot<T = any>(options: GqlModuleOptions<T>): DynamicModule;
21
22
/**
23
* Configure GraphQL module asynchronously using factories, classes, or existing providers
24
* @param options - Async configuration options
25
* @returns Dynamic module for NestJS
26
*/
27
static forRootAsync<T = any>(options: GqlModuleAsyncOptions<T>): DynamicModule;
28
29
/**
30
* Create feature module for GraphQL (typically used in feature modules)
31
* @returns Dynamic module for NestJS
32
*/
33
static forFeature(): DynamicModule;
34
}
35
```
36
37
**Usage Examples:**
38
39
```typescript
40
import { Module } from "@nestjs/common";
41
import { GraphQLModule } from "@nestjs/graphql";
42
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
43
44
// Synchronous configuration
45
@Module({
46
imports: [
47
GraphQLModule.forRoot<ApolloDriverConfig>({
48
driver: ApolloDriver,
49
autoSchemaFile: true,
50
playground: true,
51
introspection: true,
52
}),
53
],
54
})
55
export class AppModule {}
56
57
// Asynchronous configuration with factory
58
@Module({
59
imports: [
60
GraphQLModule.forRootAsync<ApolloDriverConfig>({
61
driver: ApolloDriver,
62
useFactory: async (configService: ConfigService) => ({
63
autoSchemaFile: true,
64
playground: configService.get('NODE_ENV') === 'development',
65
introspection: true,
66
context: ({ req }) => ({ user: req.user }),
67
}),
68
inject: [ConfigService],
69
}),
70
],
71
})
72
export class AppModule {}
73
```
74
75
### Module Options Interface
76
77
Complete configuration interface for GraphQL module setup with all available options.
78
79
```typescript { .api }
80
/**
81
* Configuration options for GraphQL module
82
*/
83
interface GqlModuleOptions<T = any> {
84
/** GraphQL driver class (e.g., ApolloDriver, ExpressGraphQLDriver) */
85
driver?: new (...args: any[]) => GraphQLDriver;
86
87
/** Path for auto-generated schema file or boolean to enable/disable */
88
autoSchemaFile?: string | boolean;
89
90
/** Paths to GraphQL schema definition files for schema-first approach */
91
typePaths?: string[];
92
93
/** Options for TypeScript definitions generation */
94
definitions?: DefinitionsGeneratorOptions;
95
96
/** Array of resolver classes to register */
97
resolvers?: any[];
98
99
/** GraphQL context function or object */
100
context?: any;
101
102
/** Enable/disable GraphQL Playground */
103
playground?: boolean;
104
105
/** Enable/disable GraphQL introspection */
106
introspection?: boolean;
107
108
/** Enable/disable debug mode */
109
debug?: boolean;
110
111
/** CORS configuration */
112
cors?: boolean | any;
113
114
/** Options for schema building process */
115
buildSchemaOptions?: BuildSchemaOptions;
116
117
/** Custom field middleware */
118
fieldMiddleware?: FieldMiddleware[];
119
120
/** Global pipes for validation/transformation */
121
globalPipes?: PipeTransform[];
122
123
/** GraphQL endpoint path */
124
path?: string;
125
126
/** Custom plugins */
127
plugins?: any[];
128
129
/** Custom formatters for errors and responses */
130
formatError?: (error: GraphQLError) => any;
131
formatResponse?: (response: any) => any;
132
133
/** Schema transformation functions */
134
transformSchema?: (schema: GraphQLSchema) => GraphQLSchema;
135
136
/** Subscription configuration */
137
subscriptions?: SubscriptionConfig;
138
139
/** Custom schema directives */
140
schemaDirectives?: Record<string, any>;
141
142
/** Custom type definitions to include in schema */
143
typeDefs?: string | string[];
144
145
/** Custom resolvers map */
146
resolverValidationOptions?: any;
147
148
/** Upload configuration for file uploads */
149
uploads?: boolean | any;
150
}
151
```
152
153
### Async Configuration Options
154
155
Interface for asynchronous module configuration using factories, classes, or existing providers.
156
157
```typescript { .api }
158
/**
159
* Asynchronous configuration options for GraphQL module
160
*/
161
interface GqlModuleAsyncOptions<T = any> {
162
/** Modules to import for dependency injection */
163
imports?: any[];
164
165
/** Factory function to create options asynchronously */
166
useFactory?: (...args: any[]) => Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;
167
168
/** Dependencies to inject into factory function */
169
inject?: any[];
170
171
/** Class that implements GqlOptionsFactory interface */
172
useClass?: Type<GqlOptionsFactory<T>>;
173
174
/** Existing provider that implements GqlOptionsFactory interface */
175
useExisting?: Type<GqlOptionsFactory<T>>;
176
177
/** GraphQL driver (can be specified here instead of in options) */
178
driver?: new (...args: any[]) => GraphQLDriver;
179
}
180
```
181
182
### Options Factory Interface
183
184
Interface for creating GraphQL module options using class-based factories.
185
186
```typescript { .api }
187
/**
188
* Interface for GraphQL options factory classes
189
*/
190
interface GqlOptionsFactory<T = any> {
191
/**
192
* Create GraphQL module options
193
* @returns Promise resolving to options or options object
194
*/
195
createGqlOptions(): Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;
196
}
197
```
198
199
**Usage Example:**
200
201
```typescript
202
import { Injectable } from "@nestjs/common";
203
import { GqlOptionsFactory, GqlModuleOptions } from "@nestjs/graphql";
204
import { ConfigService } from "@nestjs/config";
205
206
@Injectable()
207
export class GraphQLConfigService implements GqlOptionsFactory {
208
constructor(private configService: ConfigService) {}
209
210
createGqlOptions(): GqlModuleOptions {
211
return {
212
autoSchemaFile: true,
213
playground: this.configService.get('NODE_ENV') === 'development',
214
introspection: true,
215
cors: {
216
origin: this.configService.get('ALLOWED_ORIGINS'),
217
credentials: true,
218
},
219
context: ({ req, res }) => ({
220
req,
221
res,
222
user: req.user,
223
}),
224
};
225
}
226
}
227
228
// Usage in module
229
@Module({
230
imports: [
231
GraphQLModule.forRootAsync({
232
useClass: GraphQLConfigService,
233
imports: [ConfigModule],
234
}),
235
],
236
})
237
export class AppModule {}
238
```
239
240
### Build Schema Options
241
242
Configuration options for the GraphQL schema building process.
243
244
```typescript { .api }
245
/**
246
* Options for GraphQL schema construction
247
*/
248
interface BuildSchemaOptions {
249
/** Date scalar handling mode */
250
dateScalarMode?: 'isoDate' | 'timestamp';
251
252
/** Custom scalar type mappings */
253
scalarsMap?: ScalarsTypeMap[];
254
255
/** Types to include in schema even if not referenced */
256
orphanedTypes?: Function[];
257
258
/** Global pipes for all fields */
259
globalPipes?: PipeTransform[];
260
261
/** Field-level middleware */
262
fieldMiddleware?: FieldMiddleware[];
263
264
/** Validation options for resolvers */
265
resolverValidationOptions?: ResolverValidationOptions;
266
267
/** Custom schema directives */
268
directives?: DirectiveNode[];
269
270
/** Schema-level extensions */
271
extensions?: Record<string, any>;
272
}
273
274
interface ScalarsTypeMap {
275
type: Function;
276
scalar: GraphQLScalarType;
277
}
278
```
279
280
### Driver Interface
281
282
Abstract interface that all GraphQL drivers must implement.
283
284
```typescript { .api }
285
/**
286
* Interface for GraphQL driver implementations
287
*/
288
interface GraphQLDriver<T = any> {
289
start(options: T): Promise<void>;
290
stop(): Promise<void>;
291
mergeDefaultOptions(options: T): T;
292
}
293
```
294
295
### Field Middleware Interface
296
297
Interface for implementing field-level middleware in GraphQL resolvers.
298
299
```typescript { .api }
300
/**
301
* Interface for field-level middleware
302
*/
303
interface FieldMiddleware<TSource = any, TContext = any, TArgs = any> {
304
/**
305
* Middleware function executed for each field resolution
306
* @param params - Middleware context with source, args, context, and info
307
* @returns Transformed value or original value
308
*/
309
use(params: MiddlewareContext<TSource, TContext, TArgs>): any;
310
}
311
312
interface MiddlewareContext<TSource = any, TContext = any, TArgs = any> {
313
source: TSource;
314
args: TArgs;
315
context: TContext;
316
info: GraphQLResolveInfo;
317
next: () => any;
318
}
319
```
320
321
**Usage Example:**
322
323
```typescript
324
import { FieldMiddleware, MiddlewareContext } from "@nestjs/graphql";
325
326
export class LoggingMiddleware implements FieldMiddleware {
327
use({ source, args, context, info, next }: MiddlewareContext) {
328
console.log(`Resolving field: ${info.fieldName}`);
329
const value = next();
330
console.log(`Resolved field: ${info.fieldName} with value:`, value);
331
return value;
332
}
333
}
334
335
// Apply globally in module configuration
336
GraphQLModule.forRoot({
337
buildSchemaOptions: {
338
fieldMiddleware: [LoggingMiddleware],
339
},
340
});
341
```