GraphQL integration for the NestJS framework enabling developers to build GraphQL APIs using decorators and TypeScript
npx @tessl/cli install tessl/npm-nestjs--graphql@13.1.0NestJS GraphQL is a comprehensive GraphQL integration library for the NestJS framework that enables developers to build GraphQL APIs using decorators and TypeScript. It provides both code-first and schema-first approaches, supporting advanced features like federation, subscriptions, custom scalars, and middleware. The library offers seamless integration with popular GraphQL servers and includes powerful type generation capabilities.
npm install @nestjs/graphql graphqlimport { GraphQLModule, Resolver, Query, Mutation, Field, ObjectType } from "@nestjs/graphql";
import { GraphQLSchema, GraphQLResolveInfo, DocumentNode } from "graphql";For CommonJS:
const { GraphQLModule, Resolver, Query, Mutation, Field, ObjectType } = require("@nestjs/graphql");import { Module } from "@nestjs/common";
import { GraphQLModule } from "@nestjs/graphql";
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
import { Resolver, Query, ObjectType, Field, ID } from "@nestjs/graphql";
// Define GraphQL object type
@ObjectType()
class User {
@Field(() => ID)
id: string;
@Field()
name: string;
@Field()
email: string;
}
// Define resolver
@Resolver(() => User)
class UserResolver {
@Query(() => [User])
users(): User[] {
return [
{ id: "1", name: "John Doe", email: "john@example.com" },
{ id: "2", name: "Jane Smith", email: "jane@example.com" },
];
}
}
// Configure GraphQL module
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: true,
}),
],
providers: [UserResolver],
})
export class AppModule {}NestJS GraphQL is built around several key architectural components:
Core module configuration and setup for integrating GraphQL into NestJS applications. Supports both synchronous and asynchronous configuration patterns.
export class GraphQLModule {
static forRoot<T = any>(options: GqlModuleOptions<T>): DynamicModule;
static forRootAsync<T = any>(options: GqlModuleAsyncOptions<T>): DynamicModule;
static forFeature(): DynamicModule;
}
interface GqlModuleOptions<T = any> {
driver?: new (...args: any[]) => GraphQLDriver;
autoSchemaFile?: string | boolean;
typePaths?: string[];
definitions?: DefinitionsGeneratorOptions;
resolvers?: any[];
context?: any;
playground?: boolean;
introspection?: boolean;
debug?: boolean;
cors?: boolean | any;
buildSchemaOptions?: BuildSchemaOptions;
}Comprehensive decorator system for defining GraphQL schemas using TypeScript classes. Includes decorators for types, fields, resolvers, and arguments.
// Class decorators
function ObjectType(name?: string, options?: ObjectTypeOptions): ClassDecorator;
function InputType(name?: string, options?: InputTypeOptions): ClassDecorator;
function InterfaceType(name?: string, options?: InterfaceTypeOptions): ClassDecorator;
function Resolver<T = any>(typeFunc?: T, options?: ResolverOptions): ClassDecorator;
// Method decorators
function Query(name?: string, options?: QueryOptions): MethodDecorator;
function Mutation(name?: string, options?: MutationOptions): MethodDecorator;
function Subscription(name?: string, options?: SubscriptionOptions): MethodDecorator;
function Field(typeFunc?: TypeFunc, options?: FieldOptions): PropertyDecorator & MethodDecorator;
// Parameter decorators
function Args(name?: string, options?: ArgsOptions): ParameterDecorator;
function Parent(): ParameterDecorator;
function Context(property?: string): ParameterDecorator;
function Info(): ParameterDecorator;Tools and utilities for building GraphQL resolvers including field resolvers, context access, and argument handling.
function ResolveField(name?: string, options?: FieldOptions): MethodDecorator;
function ResolveReference(): MethodDecorator;
// Execution context utilities
export class GqlExecutionContext {
static create(context: ExecutionContext): GqlExecutionContext;
getType(): string;
getRoot<T = any>(): T;
getArgs<T = any>(): T;
getContext<T = any>(): T;
getInfo(): GraphQLResolveInfo;
}
export class GqlArgumentsHost {
getRoot<T = any>(): T;
getArgs<T = any>(): T;
getContext<T = any>(): T;
getInfo(): GraphQLResolveInfo;
}Type transformation utilities, custom scalar definitions, and helper functions for creating complex GraphQL types.
// Type transformation utilities
function PartialType<T>(classRef: Type<T>, decorator?: ClassDecorator): Type<Partial<T>>;
function PickType<T, K extends keyof T>(classRef: Type<T>, keys: readonly K[], decorator?: ClassDecorator): Type<Pick<T, K>>;
function OmitType<T, K extends keyof T>(classRef: Type<T>, keys: readonly K[], decorator?: ClassDecorator): Type<Omit<T, K>>;
function IntersectionType<A, B>(classARef: Type<A>, classBRef: Type<B>, decorator?: ClassDecorator): Type<A & B>;
// Union and enum utilities
function createUnionType(options: UnionOptions): GraphQLUnionType;
function registerEnumType(enumObject: object, options: EnumOptions): void;
// Built-in scalars
export const Int: GraphQLScalarType;
export const Float: GraphQLScalarType;
export const String: GraphQLScalarType;
export const Boolean: GraphQLScalarType;
export const ID: GraphQLScalarType;
export const GraphQLISODateTime: GraphQLScalarType;
export const GraphQLTimestamp: GraphQLScalarType;Apollo Federation capabilities for building distributed GraphQL architectures with reference resolvers and federated schema generation.
export class GraphQLFederationFactory {
mergeWithSchema(schema: GraphQLSchema): GraphQLSchema;
}
export class GraphQLFederationDefinitionsFactory {
generate(options: DefinitionsGeneratorOptions): Promise<void>;
}
function ResolveReference(): MethodDecorator;Advanced schema building utilities, type loading, and definition generation for both code-first and schema-first approaches.
export class GraphQLFactory {
create(options: GqlModuleOptions): Promise<GraphQLSchema>;
}
export class GraphQLSchemaFactory {
create(metadata: BuildSchemaOptions): GraphQLSchema;
}
export class GraphQLTypesLoader {
mergeTypesByPaths(paths: string[]): string;
}
export class GraphQLDefinitionsFactory {
generate(options: GenerateOptions): Promise<void>;
}
export class GraphQLSchemaHost {
get schema(): GraphQLSchema;
}Schema Building and Generation
GraphQL subscription support with WebSocket integration and subscription lifecycle management.
export class GqlSubscriptionService {
// Subscription management methods
}
type GraphQLWsSubscriptionsConfig = {
host?: string;
port?: number;
path?: string;
};
type SubscriptionConfig = GraphQLWsSubscriptionsConfig | GraphQLSubscriptionTransportWsConfig;Core service classes for exploring metadata, handling execution context, and managing GraphQL functionality.
export class BaseExplorerService {
explore(): any[];
}
export class ResolversExplorerService extends BaseExplorerService {
exploreResolvers(modules: Module[]): ResolverMetadata[];
}
export class ScalarsExplorerService extends BaseExplorerService {
exploreScalars(modules: Module[]): ScalarMetadata[];
}
export class GraphQLAstExplorer {
explore(documentNode: DocumentNode, outputPath: string, mode: GenerateOptions['outputAs']): Promise<void>;
}
export class GraphQLTypesLoader {
mergeTypesByPaths(paths: string[]): string;
}
export class TypeMetadataStorage {
addFieldMetadata(metadata: FieldMetadata): void;
addClassMetadata(metadata: ClassMetadata): void;
compileClassMetadata(target: Function): ClassMetadata;
}Core interfaces and types used throughout the library:
interface GqlModuleAsyncOptions<T = any> {
imports?: any[];
useFactory?: (...args: any[]) => Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;
inject?: any[];
useClass?: Type<GqlOptionsFactory<T>>;
useExisting?: Type<GqlOptionsFactory<T>>;
}
interface GqlOptionsFactory<T = any> {
createGqlOptions(): Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;
}
type ReturnTypeFunc = (returns?: void) => Function | object | symbol;
type GqlTypeReference = Function | object | symbol | [Function | object | symbol];
interface BuildSchemaOptions {
dateScalarMode?: 'isoDate' | 'timestamp';
scalarsMap?: ScalarsTypeMap[];
orphanedTypes?: Function[];
globalPipes?: PipeTransform[];
fieldMiddleware?: FieldMiddleware[];
}
interface FieldMiddleware<TSource = any, TContext = any, TArgs = any> {
use(params: MiddlewareContext<TSource, TContext, TArgs>): any;
}
interface MiddlewareContext<TSource = any, TContext = any, TArgs = any> {
source: TSource;
args: TArgs;
context: TContext;
info: GraphQLResolveInfo;
next: NextFn;
}
type NextFn<T = any> = () => Promise<T> | T;
interface ScalarsTypeMap {
type: Function;
scalar: GraphQLScalarType;
}
interface DefinitionsGeneratorOptions {
typePaths: string[];
path: string;
outputAs?: 'class' | 'interface';
watch?: boolean;
debug?: boolean;
skipResolverArgs?: boolean;
additionalHeaders?: string[];
federation?: boolean;
}
interface UnionOptions<T = any> {
name: string;
types: () => readonly [Function, ...Function[]];
resolveType?: (value: T) => Function | string | Promise<Function | string>;
description?: string;
}
interface EnumOptions<T = any> {
name: string;
description?: string;
valuesMap?: Record<string, EnumValueConfig>;
}
interface EnumValueConfig {
value?: any;
description?: string;
deprecationReason?: string;
}
type PipeTransform<T = any, R = any> = {
transform(value: T, metadata: ArgumentMetadata): R;
};
interface ArgumentMetadata {
type: 'body' | 'query' | 'param' | 'custom';
metatype?: Type<unknown> | undefined;
data?: string | undefined;
}
type Type<T = any> = new (...args: any[]) => T;
interface ExecutionContext {
getClass<T = any>(): Type<T>;
getHandler(): Function;
getArgs<T extends Array<any> = any[]>(): T;
getArgByIndex<T = any>(index: number): T;
switchToRpc(): RpcArgumentsHost;
switchToHttp(): HttpArgumentsHost;
switchToWs(): WsArgumentsHost;
getType<TContext extends string = ContextType>(): TContext;
}