Overview
Build a GraphQL API with Apollo. Supports code-first schema generation and subscriptions.
Features
- Apollo Server integration
- Code-first schema generation
- Custom error formatting
- GraphQL subscriptions
Installation
npx hanma add nest-graphql --framework nest
Dependencies
@nestjs/graphql, @nestjs/apollo, @apollo/server, graphql
Code
import { Module } from "@nestjs/common";
import { GraphQLModule } from "@nestjs/graphql";
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
import { join } from "path";
export interface GqlContext {
req: Request;
res: Response;
user?: { id: string; email: string; roles: string[] };
}
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
// Code-first approach - schema generated from decorators
autoSchemaFile: join(process.cwd(), "src/schema.gql"),
sortSchema: true,
// Enable GraphQL Playground in development
playground: process.env.NODE_ENV !== "production",
introspection: process.env.NODE_ENV !== "production",
// Context available in all resolvers
context: ({ req, res }): GqlContext => ({
req,
res,
user: (req as any).user, // Populated by auth middleware
}),
// Custom error formatting
formatError: (error) => {
const graphQLFormattedError = {
message: error.message,
code: error.extensions?.code || "INTERNAL_SERVER_ERROR",
path: error.path,
};
// Include stack trace in development
if (process.env.NODE_ENV === "development") {
return {
...graphQLFormattedError,
extensions: error.extensions,
};
}
return graphQLFormattedError;
},
// Subscriptions configuration (optional)
subscriptions: {
"graphql-ws": true,
"subscriptions-transport-ws": false,
},
}),
],
})
export class GraphqlConfigModule {}
Usage
// Import in AppModule
@Module({
imports: [GraphqlConfigModule],
})
Dependencies
@nestjs/graphql@nestjs/apollo@apollo/servergraphql
Frequently Asked Questions
How do I install GraphQL Module?
Run the following command:
npx hanma add nest-graphql --framework nestWhat dependencies are required?
This snippet requires: @nestjs/graphql, @nestjs/apollo, @apollo/server, graphql. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to
src/graphql/graphql.module.ts.Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.