Instruction file imported from Rockuo/ts-next-gql-neon (
.github/instructions/graphql.instructions.md). Copyright stays with the author.
GraphQL Architecture
This document describes the GraphQL architecture used in this project.
Overview
The GraphQL API is built using Apollo Server 4 integrated with Next.js App Router.
File Structure
app/graphql/
├── resolvers.ts # Auto-aggregates all resolvers
├── typeDefs.ts # Auto-aggregates all type definitions
├── generated/ # Auto-generated files (DO NOT EDIT MANUALLY)
│ ├── gql.ts
│ ├── graphql.ts
│ ├── index.ts
│ ├── fragment-masking.ts
│ └── schema.graphql
├── mutations/
│ ├── index.ts # Export all mutations
│ ├── login.ts
│ └── register.ts
├── queries/
│ ├── index.ts # Export all queries
│ └── refreshCredentials.ts
└── types/
├── index.ts # Export all types
└── User.ts
Creating a Query
- Create a new file in
app/graphql/queries/ - Define the query with
typeDefandresolver - Export from
app/graphql/queries/index.ts - Run
npm run gql:schema
Creating a Mutation
- Create a new file in
app/graphql/mutations/ - Define the mutation with
typeDefandresolver - Export from
app/graphql/mutations/index.ts - Run
npm run gql:schema
Creating a Type
- Create a new file in
app/graphql/types/ - Define the GraphQL type as a string export
- Export from
app/graphql/types/index.ts - Run
npm run gql:schema
Using Queries/Mutations in Components
import { gql } from '@/app/graphql/generated';
import { useQuery, useMutation } from '@apollo/client/react';
const MY_QUERY = gql(`
query MyQuery($id: ID!) {
myQuery(id: $id) {
field1
field2
}
}
`);
// In component:
const { data, loading, error } = useQuery(MY_QUERY, {
variables: { id: 'some-id' }
});
Authentication Context
Resolvers receive a context object with the authenticated user:
resolver: async (_: unknown, args: Args, context: { user: LoggedInUser }) => {
if (!context.user) {
throw new Error('Authentication required');
}
// ... implementation
}