or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-nestjs--graphql

GraphQL integration for the NestJS framework enabling developers to build GraphQL APIs using decorators and TypeScript

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@nestjs/graphql@13.1.x

To install, run

npx @tessl/cli install tessl/npm-nestjs--graphql@13.1.0

0

# NestJS GraphQL

1

2

NestJS 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.

3

4

## Package Information

5

6

- **Package Name**: @nestjs/graphql

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @nestjs/graphql graphql`

10

11

## Core Imports

12

13

```typescript

14

import { GraphQLModule, Resolver, Query, Mutation, Field, ObjectType } from "@nestjs/graphql";

15

import { GraphQLSchema, GraphQLResolveInfo, DocumentNode } from "graphql";

16

```

17

18

For CommonJS:

19

20

```javascript

21

const { GraphQLModule, Resolver, Query, Mutation, Field, ObjectType } = require("@nestjs/graphql");

22

```

23

24

## Basic Usage

25

26

```typescript

27

import { Module } from "@nestjs/common";

28

import { GraphQLModule } from "@nestjs/graphql";

29

import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";

30

import { Resolver, Query, ObjectType, Field, ID } from "@nestjs/graphql";

31

32

// Define GraphQL object type

33

@ObjectType()

34

class User {

35

@Field(() => ID)

36

id: string;

37

38

@Field()

39

name: string;

40

41

@Field()

42

email: string;

43

}

44

45

// Define resolver

46

@Resolver(() => User)

47

class UserResolver {

48

@Query(() => [User])

49

users(): User[] {

50

return [

51

{ id: "1", name: "John Doe", email: "john@example.com" },

52

{ id: "2", name: "Jane Smith", email: "jane@example.com" },

53

];

54

}

55

}

56

57

// Configure GraphQL module

58

@Module({

59

imports: [

60

GraphQLModule.forRoot<ApolloDriverConfig>({

61

driver: ApolloDriver,

62

autoSchemaFile: true,

63

}),

64

],

65

providers: [UserResolver],

66

})

67

export class AppModule {}

68

```

69

70

## Architecture

71

72

NestJS GraphQL is built around several key architectural components:

73

74

- **Decorator System**: TypeScript decorators for schema definition (@ObjectType, @Resolver, @Query, etc.)

75

- **Schema Generation**: Automatic GraphQL schema generation from TypeScript classes and decorators

76

- **Driver Architecture**: Pluggable drivers for different GraphQL servers (Apollo, Express GraphQL, etc.)

77

- **Type System**: Full TypeScript integration with automatic type inference and validation

78

- **Federation Support**: Apollo Federation capabilities for microservice architectures

79

- **Code-First and Schema-First**: Support for both development approaches with seamless switching

80

81

## Capabilities

82

83

### Module Configuration

84

85

Core module configuration and setup for integrating GraphQL into NestJS applications. Supports both synchronous and asynchronous configuration patterns.

86

87

```typescript { .api }

88

export class GraphQLModule {

89

static forRoot<T = any>(options: GqlModuleOptions<T>): DynamicModule;

90

static forRootAsync<T = any>(options: GqlModuleAsyncOptions<T>): DynamicModule;

91

static forFeature(): DynamicModule;

92

}

93

94

interface GqlModuleOptions<T = any> {

95

driver?: new (...args: any[]) => GraphQLDriver;

96

autoSchemaFile?: string | boolean;

97

typePaths?: string[];

98

definitions?: DefinitionsGeneratorOptions;

99

resolvers?: any[];

100

context?: any;

101

playground?: boolean;

102

introspection?: boolean;

103

debug?: boolean;

104

cors?: boolean | any;

105

buildSchemaOptions?: BuildSchemaOptions;

106

}

107

```

108

109

[Module Configuration](./module-configuration.md)

110

111

### Schema Definition Decorators

112

113

Comprehensive decorator system for defining GraphQL schemas using TypeScript classes. Includes decorators for types, fields, resolvers, and arguments.

114

115

```typescript { .api }

116

// Class decorators

117

function ObjectType(name?: string, options?: ObjectTypeOptions): ClassDecorator;

118

function InputType(name?: string, options?: InputTypeOptions): ClassDecorator;

119

function InterfaceType(name?: string, options?: InterfaceTypeOptions): ClassDecorator;

120

function Resolver<T = any>(typeFunc?: T, options?: ResolverOptions): ClassDecorator;

121

122

// Method decorators

123

function Query(name?: string, options?: QueryOptions): MethodDecorator;

124

function Mutation(name?: string, options?: MutationOptions): MethodDecorator;

125

function Subscription(name?: string, options?: SubscriptionOptions): MethodDecorator;

126

function Field(typeFunc?: TypeFunc, options?: FieldOptions): PropertyDecorator & MethodDecorator;

127

128

// Parameter decorators

129

function Args(name?: string, options?: ArgsOptions): ParameterDecorator;

130

function Parent(): ParameterDecorator;

131

function Context(property?: string): ParameterDecorator;

132

function Info(): ParameterDecorator;

133

```

134

135

[Schema Definition Decorators](./schema-decorators.md)

136

137

### Resolver Development

138

139

Tools and utilities for building GraphQL resolvers including field resolvers, context access, and argument handling.

140

141

```typescript { .api }

142

function ResolveField(name?: string, options?: FieldOptions): MethodDecorator;

143

function ResolveReference(): MethodDecorator;

144

145

// Execution context utilities

146

export class GqlExecutionContext {

147

static create(context: ExecutionContext): GqlExecutionContext;

148

getType(): string;

149

getRoot<T = any>(): T;

150

getArgs<T = any>(): T;

151

getContext<T = any>(): T;

152

getInfo(): GraphQLResolveInfo;

153

}

154

155

export class GqlArgumentsHost {

156

getRoot<T = any>(): T;

157

getArgs<T = any>(): T;

158

getContext<T = any>(): T;

159

getInfo(): GraphQLResolveInfo;

160

}

161

```

162

163

[Resolver Development](./resolvers.md)

164

165

### Type System and Utilities

166

167

Type transformation utilities, custom scalar definitions, and helper functions for creating complex GraphQL types.

168

169

```typescript { .api }

170

// Type transformation utilities

171

function PartialType<T>(classRef: Type<T>, decorator?: ClassDecorator): Type<Partial<T>>;

172

function PickType<T, K extends keyof T>(classRef: Type<T>, keys: readonly K[], decorator?: ClassDecorator): Type<Pick<T, K>>;

173

function OmitType<T, K extends keyof T>(classRef: Type<T>, keys: readonly K[], decorator?: ClassDecorator): Type<Omit<T, K>>;

174

function IntersectionType<A, B>(classARef: Type<A>, classBRef: Type<B>, decorator?: ClassDecorator): Type<A & B>;

175

176

// Union and enum utilities

177

function createUnionType(options: UnionOptions): GraphQLUnionType;

178

function registerEnumType(enumObject: object, options: EnumOptions): void;

179

180

// Built-in scalars

181

export const Int: GraphQLScalarType;

182

export const Float: GraphQLScalarType;

183

export const String: GraphQLScalarType;

184

export const Boolean: GraphQLScalarType;

185

export const ID: GraphQLScalarType;

186

export const GraphQLISODateTime: GraphQLScalarType;

187

export const GraphQLTimestamp: GraphQLScalarType;

188

```

189

190

[Type System and Utilities](./type-system.md)

191

192

### Federation Support

193

194

Apollo Federation capabilities for building distributed GraphQL architectures with reference resolvers and federated schema generation.

195

196

```typescript { .api }

197

export class GraphQLFederationFactory {

198

mergeWithSchema(schema: GraphQLSchema): GraphQLSchema;

199

}

200

201

export class GraphQLFederationDefinitionsFactory {

202

generate(options: DefinitionsGeneratorOptions): Promise<void>;

203

}

204

205

function ResolveReference(): MethodDecorator;

206

```

207

208

[Federation Support](./federation.md)

209

210

### Schema Building and Generation

211

212

Advanced schema building utilities, type loading, and definition generation for both code-first and schema-first approaches.

213

214

```typescript { .api }

215

export class GraphQLFactory {

216

create(options: GqlModuleOptions): Promise<GraphQLSchema>;

217

}

218

219

export class GraphQLSchemaFactory {

220

create(metadata: BuildSchemaOptions): GraphQLSchema;

221

}

222

223

export class GraphQLTypesLoader {

224

mergeTypesByPaths(paths: string[]): string;

225

}

226

227

export class GraphQLDefinitionsFactory {

228

generate(options: GenerateOptions): Promise<void>;

229

}

230

231

export class GraphQLSchemaHost {

232

get schema(): GraphQLSchema;

233

}

234

```

235

236

[Schema Building and Generation](./schema-building.md)

237

238

### Subscriptions

239

240

GraphQL subscription support with WebSocket integration and subscription lifecycle management.

241

242

```typescript { .api }

243

export class GqlSubscriptionService {

244

// Subscription management methods

245

}

246

247

type GraphQLWsSubscriptionsConfig = {

248

host?: string;

249

port?: number;

250

path?: string;

251

};

252

253

type SubscriptionConfig = GraphQLWsSubscriptionsConfig | GraphQLSubscriptionTransportWsConfig;

254

```

255

256

[Subscriptions](./subscriptions.md)

257

258

### Service Classes

259

260

Core service classes for exploring metadata, handling execution context, and managing GraphQL functionality.

261

262

```typescript { .api }

263

export class BaseExplorerService {

264

explore(): any[];

265

}

266

267

export class ResolversExplorerService extends BaseExplorerService {

268

exploreResolvers(modules: Module[]): ResolverMetadata[];

269

}

270

271

export class ScalarsExplorerService extends BaseExplorerService {

272

exploreScalars(modules: Module[]): ScalarMetadata[];

273

}

274

275

export class GraphQLAstExplorer {

276

explore(documentNode: DocumentNode, outputPath: string, mode: GenerateOptions['outputAs']): Promise<void>;

277

}

278

279

export class GraphQLTypesLoader {

280

mergeTypesByPaths(paths: string[]): string;

281

}

282

283

export class TypeMetadataStorage {

284

addFieldMetadata(metadata: FieldMetadata): void;

285

addClassMetadata(metadata: ClassMetadata): void;

286

compileClassMetadata(target: Function): ClassMetadata;

287

}

288

```

289

290

[Service Classes](./services.md)

291

292

## Types

293

294

Core interfaces and types used throughout the library:

295

296

```typescript { .api }

297

interface GqlModuleAsyncOptions<T = any> {

298

imports?: any[];

299

useFactory?: (...args: any[]) => Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;

300

inject?: any[];

301

useClass?: Type<GqlOptionsFactory<T>>;

302

useExisting?: Type<GqlOptionsFactory<T>>;

303

}

304

305

interface GqlOptionsFactory<T = any> {

306

createGqlOptions(): Promise<GqlModuleOptions<T>> | GqlModuleOptions<T>;

307

}

308

309

type ReturnTypeFunc = (returns?: void) => Function | object | symbol;

310

type GqlTypeReference = Function | object | symbol | [Function | object | symbol];

311

312

interface BuildSchemaOptions {

313

dateScalarMode?: 'isoDate' | 'timestamp';

314

scalarsMap?: ScalarsTypeMap[];

315

orphanedTypes?: Function[];

316

globalPipes?: PipeTransform[];

317

fieldMiddleware?: FieldMiddleware[];

318

}

319

320

interface FieldMiddleware<TSource = any, TContext = any, TArgs = any> {

321

use(params: MiddlewareContext<TSource, TContext, TArgs>): any;

322

}

323

324

interface MiddlewareContext<TSource = any, TContext = any, TArgs = any> {

325

source: TSource;

326

args: TArgs;

327

context: TContext;

328

info: GraphQLResolveInfo;

329

next: NextFn;

330

}

331

332

type NextFn<T = any> = () => Promise<T> | T;

333

334

interface ScalarsTypeMap {

335

type: Function;

336

scalar: GraphQLScalarType;

337

}

338

339

interface DefinitionsGeneratorOptions {

340

typePaths: string[];

341

path: string;

342

outputAs?: 'class' | 'interface';

343

watch?: boolean;

344

debug?: boolean;

345

skipResolverArgs?: boolean;

346

additionalHeaders?: string[];

347

federation?: boolean;

348

}

349

350

interface UnionOptions<T = any> {

351

name: string;

352

types: () => readonly [Function, ...Function[]];

353

resolveType?: (value: T) => Function | string | Promise<Function | string>;

354

description?: string;

355

}

356

357

interface EnumOptions<T = any> {

358

name: string;

359

description?: string;

360

valuesMap?: Record<string, EnumValueConfig>;

361

}

362

363

interface EnumValueConfig {

364

value?: any;

365

description?: string;

366

deprecationReason?: string;

367

}

368

369

type PipeTransform<T = any, R = any> = {

370

transform(value: T, metadata: ArgumentMetadata): R;

371

};

372

373

interface ArgumentMetadata {

374

type: 'body' | 'query' | 'param' | 'custom';

375

metatype?: Type<unknown> | undefined;

376

data?: string | undefined;

377

}

378

379

type Type<T = any> = new (...args: any[]) => T;

380

381

interface ExecutionContext {

382

getClass<T = any>(): Type<T>;

383

getHandler(): Function;

384

getArgs<T extends Array<any> = any[]>(): T;

385

getArgByIndex<T = any>(index: number): T;

386

switchToRpc(): RpcArgumentsHost;

387

switchToHttp(): HttpArgumentsHost;

388

switchToWs(): WsArgumentsHost;

389

getType<TContext extends string = ContextType>(): TContext;

390

}

391

```