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
Comprehensive decorator system for defining GraphQL schemas using TypeScript classes. This decorator-based approach enables code-first GraphQL schema development where TypeScript classes and decorators automatically generate the GraphQL schema definition.
Decorators for marking TypeScript classes as GraphQL types, resolvers, and schema elements.
/**
* Marks a TypeScript class as a GraphQL Object Type
* @param name - Optional GraphQL type name (defaults to class name)
* @param options - Configuration options for the object type
*/
function ObjectType(name?: string, options?: ObjectTypeOptions): ClassDecorator;
/**
* Marks a TypeScript class as a GraphQL Input Type for mutations and field arguments
* @param name - Optional GraphQL input type name (defaults to class name)
* @param options - Configuration options for the input type
*/
function InputType(name?: string, options?: InputTypeOptions): ClassDecorator;
/**
* Marks a TypeScript class as a GraphQL Interface Type
* @param name - Optional GraphQL interface name (defaults to class name)
* @param options - Configuration options for the interface type
*/
function InterfaceType(name?: string, options?: InterfaceTypeOptions): ClassDecorator;
/**
* Marks a TypeScript class as a GraphQL Resolver for queries, mutations, and subscriptions
* @param typeOrName - Optional type function, string name, or class reference this resolver handles
* @param options - Configuration options for the resolver
*/
function Resolver<T = any>(typeOrName?: string | Function | ReturnTypeFunc, options?: ResolverOptions): ClassDecorator;
/**
* Marks a TypeScript class as a GraphQL Arguments Type for grouping resolver arguments
* @param options - Configuration options for the arguments type
*/
function ArgsType(options?: ArgsTypeOptions): ClassDecorator;
/**
* Marks a TypeScript class as a custom GraphQL Scalar Type
* @param name - The GraphQL scalar name
* @param typeFunc - Optional function returning the scalar type
*/
function Scalar(name: string, typeFunc?: () => GraphQLScalarType): ClassDecorator;Usage Examples:
import { ObjectType, InputType, InterfaceType, Resolver, ArgsType, Field, ID } from "@nestjs/graphql";
// Object Type
@ObjectType()
class User {
@Field(() => ID)
id: string;
@Field()
name: string;
@Field({ nullable: true })
email?: string;
}
// Input Type
@InputType()
class CreateUserInput {
@Field()
name: string;
@Field()
email: string;
}
// Interface Type
@InterfaceType()
abstract class Node {
@Field(() => ID)
id: string;
}
// Arguments Type
@ArgsType()
class GetUsersArgs {
@Field({ nullable: true })
limit?: number;
@Field({ nullable: true })
offset?: number;
}
// Resolver
@Resolver(() => User)
class UserResolver {
// resolver methods here
}
// Custom Scalar
@Scalar('DateTime')
class DateTimeScalar {
// scalar implementation
}Decorators for defining GraphQL operations and field resolvers on methods.
/**
* Marks a method as a GraphQL Query operation
* @param nameOrTypeFunc - Optional query name or return type function
* @param options - Configuration options for the query
*/
function Query(nameOrTypeFunc?: string | ReturnTypeFunc, options?: QueryOptions): MethodDecorator;
/**
* Marks a method as a GraphQL Mutation operation
* @param nameOrTypeFunc - Optional mutation name or return type function
* @param options - Configuration options for the mutation
*/
function Mutation(nameOrTypeFunc?: string | ReturnTypeFunc, options?: MutationOptions): MethodDecorator;
/**
* Marks a method as a GraphQL Subscription operation
* @param nameOrTypeFunc - Optional subscription name or return type function
* @param options - Configuration options for the subscription
*/
function Subscription(nameOrTypeFunc?: string | ReturnTypeFunc, options?: SubscriptionOptions): MethodDecorator;
/**
* Marks a property or method as a GraphQL Field
* @param typeFunc - Function returning the GraphQL type for this field
* @param options - Configuration options for the field
*/
function Field(typeFunc?: ReturnTypeFunc, options?: FieldOptions): PropertyDecorator & MethodDecorator;
/**
* Marks a method as a GraphQL Field Resolver for computed fields
* @param nameOrTypeFunc - Optional field name or return type function
* @param options - Configuration options for the field resolver
*/
function ResolveField(nameOrTypeFunc?: string | ReturnTypeFunc, options?: ResolveFieldOptions): MethodDecorator;
/**
* Marks a method as a GraphQL Reference Resolver for Apollo Federation
*/
function ResolveReference(): MethodDecorator;
/**
* Legacy alias for ResolveField (deprecated)
* @param name - Optional field name
* @param options - Configuration options
*/
function ResolveProperty(name?: string, options?: FieldOptions): MethodDecorator;Usage Examples:
import { Resolver, Query, Mutation, Subscription, Field, ResolveField, Args } from "@nestjs/graphql";
@Resolver(() => User)
class UserResolver {
// Query operation
@Query(() => [User])
users(): User[] {
return [];
}
// Mutation operation
@Mutation(() => User)
createUser(@Args('input') input: CreateUserInput): User {
return new User();
}
// Subscription operation
@Subscription(() => User)
userAdded() {
return this.pubSub.asyncIterator('userAdded');
}
// Field resolver for computed fields
@ResolveField(() => String)
fullName(@Parent() user: User): string {
return `${user.firstName} ${user.lastName}`;
}
// Federation reference resolver
@ResolveReference()
resolveReference(reference: { __typename: string; id: string }): User {
return this.findUserById(reference.id);
}
}Decorators for extracting data from GraphQL resolver context and arguments.
/**
* Extracts GraphQL arguments from resolver parameters
* @param name - Optional argument name (extracts all args if not specified)
* @param options - Configuration options for argument validation
* @param pipes - Optional validation pipes
*/
function Args(name?: string, options?: ArgsOptions, ...pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator;
/**
* Injects the parent/root object in field resolvers
* @param pipes - Optional validation pipes
*/
function Parent(...pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator;
/**
* Alias for Parent decorator
*/
function Root(): ParameterDecorator;
/**
* Injects GraphQL context or specific context properties
* @param property - Optional property path to extract from context
* @param pipes - Optional validation pipes
*/
function Context(property?: string, ...pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator;
/**
* Injects GraphQL resolve info object containing field selection and metadata
* @param pipes - Optional validation pipes
*/
function Info(...pipes: (Type<PipeTransform> | PipeTransform)[]): ParameterDecorator;Usage Examples:
import { Resolver, Query, Args, Parent, Context, Info } from "@nestjs/graphql";
import { GraphQLResolveInfo } from "graphql";
@Resolver(() => User)
class UserResolver {
// Extract specific argument
@Query(() => User)
user(@Args('id') id: string): User {
return this.findUserById(id);
}
// Extract all arguments
@Query(() => [User])
users(@Args() args: GetUsersArgs): User[] {
return this.findUsers(args);
}
// Use parent object in field resolver
@ResolveField(() => [Post])
posts(@Parent() user: User): Post[] {
return this.findPostsByUserId(user.id);
}
// Access GraphQL context
@Query(() => User)
me(@Context() context: { user: User }): User {
return context.user;
}
// Access specific context property
@Query(() => User)
currentUser(@Context('user') user: User): User {
return user;
}
// Access resolve info
@Query(() => [User])
users(@Info() info: GraphQLResolveInfo): User[] {
const fields = this.getSelectedFields(info);
return this.findUsersWithFields(fields);
}
}Decorators for schema metadata and field configuration.
/**
* Applies GraphQL directives to schema elements
* @param sdl - GraphQL directive definition language string
*/
function Directive(sdl: string): PropertyDecorator;
/**
* Adds extensions metadata to schema elements
* @param value - Extension data to attach
*/
function Extensions(value: Record<string, any>): PropertyDecorator;
/**
* Excludes fields from GraphQL schema generation
*/
function HideField(): PropertyDecorator;Usage Examples:
import { ObjectType, Field, Directive, Extensions, HideField } from "@nestjs/graphql";
@ObjectType()
class User {
@Field()
@Directive('@deprecated(reason: "Use fullName instead")')
name: string;
@Field()
@Extensions({ complexity: 10 })
fullName: string;
@HideField()
internalId: string; // This field won't appear in GraphQL schema
}Configuration interfaces for customizing decorator behavior.
/**
* Options for ObjectType decorator
*/
interface ObjectTypeOptions {
/** Custom description for the GraphQL type */
description?: string;
/** Interfaces this type implements */
implements?: Function | Function[] | (() => Function | Function[]);
/** Whether this type is abstract */
isAbstract?: boolean;
/** Whether to inherit description from interfaces */
inheritDescription?: boolean;
}
/**
* Options for InputType decorator
*/
interface InputTypeOptions {
/** Custom description for the GraphQL input type */
description?: string;
/** Whether this input type is abstract */
isAbstract?: boolean;
}
/**
* Options for InterfaceType decorator
*/
interface InterfaceTypeOptions {
/** Custom description for the GraphQL interface type */
description?: string;
/** Whether this interface type is abstract */
isAbstract?: boolean;
/** Custom resolve type function */
resolveType?: (value: any) => string | undefined;
/** Interfaces this interface implements */
implements?: Function | Function[] | (() => Function | Function[]);
}
/**
* Options for Field decorator
*/
interface FieldOptions {
/** Custom description for the field */
description?: string;
/** Deprecation reason */
deprecationReason?: string;
/** Whether the field can be null */
nullable?: boolean | 'items' | 'itemsAndList';
/** Default value for the field */
defaultValue?: any;
/** Field complexity for query analysis */
complexity?: number;
/** Field-specific middleware */
middleware?: FieldMiddleware[];
}
/**
* Options for Query/Mutation/Subscription decorators
*/
interface QueryOptions {
/** Custom name for the operation */
name?: string;
/** Description for the operation */
description?: string;
/** Deprecation reason */
deprecationReason?: string;
/** Query complexity */
complexity?: number;
/** Whether return type can be null */
nullable?: boolean;
}
type MutationOptions = QueryOptions;
type SubscriptionOptions = QueryOptions;
/**
* Options for ArgsType decorator
*/
interface ArgsTypeOptions {
/** Custom description for the arguments type */
description?: string;
/** Whether this arguments type is abstract */
isAbstract?: boolean;
}
/**
* Options for Args decorator
*/
interface ArgsOptions {
/** Custom name for the argument */
name?: string;
/** Description for the argument */
description?: string;
/** Whether the argument can be null */
nullable?: boolean | 'items' | 'itemsAndList';
/** Default value for the argument */
defaultValue?: any;
/** Validation pipes for the argument */
pipes?: PipeTransform[];
/** Deprecation reason */
deprecationReason?: string;
}
/**
* Options for ResolveField decorator
*/
interface ResolveFieldOptions {
/** Custom name for the field */
name?: string;
/** Description for the field */
description?: string;
/** Deprecation reason */
deprecationReason?: string;
/** Whether the field can be null */
nullable?: boolean | 'items' | 'itemsAndList';
/** Default value for the field */
defaultValue?: any;
/** Field complexity for query analysis */
complexity?: number;
/** Field-specific middleware */
middleware?: FieldMiddleware[];
}
/**
* Options for Resolver decorator
*/
interface ResolverOptions {
/** Whether this resolver is abstract (won't generate GraphQL operations) */
isAbstract?: boolean;
}Core types used throughout the decorator system.
/**
* Interface for NestJS pipe transforms used in parameter decorators
*/
interface PipeTransform<T = any, R = any> {
transform(value: T, metadata: ArgumentMetadata): R;
}
/**
* Interface for field middleware functions
*/
interface FieldMiddleware<TSource = any, TContext = any, TArgs = any, TOutput = any> {
use(params: MiddlewareContext<TSource, TContext, TArgs>): Promise<TOutput> | TOutput;
}
/**
* Middleware context passed to field middleware
*/
interface MiddlewareContext<TSource = any, TContext = any, TArgs = any> {
source: TSource;
args: TArgs;
context: TContext;
info: GraphQLResolveInfo;
next: NextFn;
}
/**
* Next function type for middleware
*/
type NextFn<T = any> = () => Promise<T> | T;
/**
* Argument metadata for pipe transforms
*/
interface ArgumentMetadata {
type: 'body' | 'query' | 'param' | 'custom';
metatype?: Type<unknown> | undefined;
data?: string | undefined;
}Helper types for defining GraphQL type references in decorators.
/**
* Function type for defining return types in decorators
*/
type ReturnTypeFunc = (returns?: void) => Function | object | symbol;
/**
* Type reference for GraphQL schema elements
*/
type GqlTypeReference = Function | object | symbol | [Function | object | symbol];
/**
* Class type reference
*/
type Type<T = any> = new (...args: any[]) => T;Usage Examples:
import { Field, ObjectType } from "@nestjs/graphql";
@ObjectType()
class User {
// Simple field with inferred type
@Field()
name: string;
// Field with explicit type function
@Field(() => String)
email: string;
// Array field
@Field(() => [String])
tags: string[];
// Optional field
@Field({ nullable: true })
bio?: string;
// Field with custom options
@Field(() => String, {
description: 'User display name',
nullable: true,
defaultValue: 'Anonymous',
})
displayName?: string;
}