GraphQL integration for the NestJS framework enabling developers to build GraphQL APIs using decorators and TypeScript
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
Main module class for integrating GraphQL into NestJS applications with static configuration methods.
/**
* Main GraphQL module for NestJS integration
*/
export class GraphQLModule {
/**
* Configure GraphQL module synchronously
* @param options - Configuration options for GraphQL module
* @returns Dynamic module for NestJS
*/
static forRoot<T = any>(options: GqlModuleOptions<T>): DynamicModule;
/**
* Configure GraphQL module asynchronously using factories, classes, or existing providers
* @param options - Async configuration options
* @returns Dynamic module for NestJS
*/
static forRootAsync<T = any>(options: GqlModuleAsyncOptions<T>): DynamicModule;
/**
* Create feature module for GraphQL (typically used in feature modules)
* @returns Dynamic module for NestJS
*/
static forFeature(): DynamicModule;
}Usage Examples:
import { Module } from "@nestjs/common";
import { GraphQLModule } from "@nestjs/graphql";
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
// Synchronous configuration
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: true,
playground: true,
introspection: true,
}),
],
})
export class AppModule {}
// Asynchronous configuration with factory
@Module({
imports: [
GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
useFactory: async (configService: ConfigService) => ({
autoSchemaFile: true,
playground: configService.get('NODE_ENV') === 'development',
introspection: true,
context: ({ req }) => ({ user: req.user }),
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}Complete configuration interface for GraphQL module setup with all available options.
/**
* Configuration options for GraphQL module
*/
interface GqlModuleOptions<T = any> {
/** GraphQL driver class (e.g., ApolloDriver, ExpressGraphQLDriver) */
driver?: new (...args: any[]) => GraphQLDriver;
/** Path for auto-generated schema file or boolean to enable/disable */
autoSchemaFile?: string | boolean;
/** Paths to GraphQL schema definition files for schema-first approach */
typePaths?: string[];
/** Options for TypeScript definitions generation */
definitions?: DefinitionsGeneratorOptions;
/** Array of resolver classes to register */
resolvers?: any[];
/** GraphQL context function or object */
context?: any;
/** Enable/disable GraphQL Playground */
playground?: boolean;
/** Enable/disable GraphQL introspection */
introspection?: boolean;
/** Enable/disable debug mode */
debug?: boolean;
/** CORS configuration */
cors?: boolean | any;
/** Options for schema building process */
buildSchemaOptions?: BuildSchemaOptions;
/** Custom field middleware */
fieldMiddleware?: FieldMiddleware[];
/** Global pipes for validation/transformation */
globalPipes?: PipeTransform[];
/** GraphQL endpoint path */
path?: string;
/** Custom plugins */
plugins?: any[];
/** Custom formatters for errors and responses */
formatError?: (error: GraphQLError) => any;
formatResponse?: (response: any) => any;
/** Schema transformation functions */
transformSchema?: (schema: GraphQLSchema) => GraphQLSchema;
/** Subscription configuration */
subscriptions?: SubscriptionConfig;
/** Custom schema directives */
schemaDirectives?: Record<string, any>;
/** Custom type definitions to include in schema */
typeDefs?: string | string[];
/** Custom resolvers map */
resolverValidationOptions?: any;
/** Upload configuration for file uploads */
uploads?: boolean | any;
}Interface for asynchronous module configuration using factories, classes, or existing providers.
/**
* Asynchronous configuration options for GraphQL module
*/
interface GqlModuleAsyncOptions<T = any> {
/** Modules to import for dependency injection */
imports?: any[];
/** Factory function to create options asynchronously */
useFactory?: (...args: any[]) => Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;
/** Dependencies to inject into factory function */
inject?: any[];
/** Class that implements GqlOptionsFactory interface */
useClass?: Type<GqlOptionsFactory<T>>;
/** Existing provider that implements GqlOptionsFactory interface */
useExisting?: Type<GqlOptionsFactory<T>>;
/** GraphQL driver (can be specified here instead of in options) */
driver?: new (...args: any[]) => GraphQLDriver;
}Interface for creating GraphQL module options using class-based factories.
/**
* Interface for GraphQL options factory classes
*/
interface GqlOptionsFactory<T = any> {
/**
* Create GraphQL module options
* @returns Promise resolving to options or options object
*/
createGqlOptions(): Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;
}Usage Example:
import { Injectable } from "@nestjs/common";
import { GqlOptionsFactory, GqlModuleOptions } from "@nestjs/graphql";
import { ConfigService } from "@nestjs/config";
@Injectable()
export class GraphQLConfigService implements GqlOptionsFactory {
constructor(private configService: ConfigService) {}
createGqlOptions(): GqlModuleOptions {
return {
autoSchemaFile: true,
playground: this.configService.get('NODE_ENV') === 'development',
introspection: true,
cors: {
origin: this.configService.get('ALLOWED_ORIGINS'),
credentials: true,
},
context: ({ req, res }) => ({
req,
res,
user: req.user,
}),
};
}
}
// Usage in module
@Module({
imports: [
GraphQLModule.forRootAsync({
useClass: GraphQLConfigService,
imports: [ConfigModule],
}),
],
})
export class AppModule {}Configuration options for the GraphQL schema building process.
/**
* Options for GraphQL schema construction
*/
interface BuildSchemaOptions {
/** Date scalar handling mode */
dateScalarMode?: 'isoDate' | 'timestamp';
/** Custom scalar type mappings */
scalarsMap?: ScalarsTypeMap[];
/** Types to include in schema even if not referenced */
orphanedTypes?: Function[];
/** Global pipes for all fields */
globalPipes?: PipeTransform[];
/** Field-level middleware */
fieldMiddleware?: FieldMiddleware[];
/** Validation options for resolvers */
resolverValidationOptions?: ResolverValidationOptions;
/** Custom schema directives */
directives?: DirectiveNode[];
/** Schema-level extensions */
extensions?: Record<string, any>;
}
interface ScalarsTypeMap {
type: Function;
scalar: GraphQLScalarType;
}Abstract interface that all GraphQL drivers must implement.
/**
* Interface for GraphQL driver implementations
*/
interface GraphQLDriver<T = any> {
start(options: T): Promise<void>;
stop(): Promise<void>;
mergeDefaultOptions(options: T): T;
}Interface for implementing field-level middleware in GraphQL resolvers.
/**
* Interface for field-level middleware
*/
interface FieldMiddleware<TSource = any, TContext = any, TArgs = any> {
/**
* Middleware function executed for each field resolution
* @param params - Middleware context with source, args, context, and info
* @returns Transformed value or original value
*/
use(params: MiddlewareContext<TSource, TContext, TArgs>): any;
}
interface MiddlewareContext<TSource = any, TContext = any, TArgs = any> {
source: TSource;
args: TArgs;
context: TContext;
info: GraphQLResolveInfo;
next: () => any;
}Usage Example:
import { FieldMiddleware, MiddlewareContext } from "@nestjs/graphql";
export class LoggingMiddleware implements FieldMiddleware {
use({ source, args, context, info, next }: MiddlewareContext) {
console.log(`Resolving field: ${info.fieldName}`);
const value = next();
console.log(`Resolved field: ${info.fieldName} with value:`, value);
return value;
}
}
// Apply globally in module configuration
GraphQLModule.forRoot({
buildSchemaOptions: {
fieldMiddleware: [LoggingMiddleware],
},
});