GraphQL Server with Apollo
backend
TypeScript
scaffolding
corporate_pm
Build a GraphQL API using Apollo Server with schema, resolvers, and data loaders.
By lucas_a
12/8/2025
Prompt
GraphQL API with Apollo Server
Create a production-ready GraphQL API for [Application] using Apollo Server.
Requirements
1. Schema Design
Define GraphQL schema with:
- [Number] main types representing [entities]
- Relationships between types
- Queries for data fetching
- Mutations for data modification
- Input types for complex arguments
2. Type Definitions
Create schema for:
- Query - Read operations ([operations])
- Mutation - Write operations ([operations])
- Subscription - Real-time updates (optional)
- Custom scalar types if needed
3. Resolvers Implementation
Implement resolvers for:
- All queries with proper data fetching
- All mutations with validation
- Nested field resolvers
- Error handling and validation
- Authentication/authorization checks
4. Performance Optimization
Include:
- DataLoaders to prevent N+1 queries
- Query complexity limits
- Depth limiting
- Caching strategies
- Pagination for lists
5. Context and Data Sources
Set up:
- Authentication context
- Database connections
- External API clients
- User permissions
6. Error Handling
Implement:
- Custom error types
- Proper error messages
- Error codes
- Stack traces in development only
Example Implementation
import { ApolloServer, gql } from "apollo-server"
import DataLoader from "dataloader"
// Schema
const typeDefs = gql`
type [TypeName] {
id: ID!
[field]: String!
[relationField]: [[RelatedType]!]!
}
type Query {
[queryName](id: ID!): [TypeName]
[listQuery]: [[TypeName]!]!
}
type Mutation {
[mutationName](input: [InputType]!): [TypeName]!
}
input [InputType] {
[field]: String!
}
`
// Resolvers
const resolvers = {
Query: {
[queryName]: async (_, { id }, { dataSources }) => {
return dataSources.[dataSource].getById(id)
}
},
Mutation: {
[mutationName]: async (_, { input }, { dataSources, user }) => {
if (!user) throw new Error(`Not authenticated`)
return dataSources.[dataSource].create(input)
}
},
[TypeName]: {
[relationField]: async (parent, _, { loaders }) => {
return loaders.[loader].load(parent.id)
}
}
}
// DataLoader for N+1 prevention
const create[Entity]Loader = () => new DataLoader(async (ids) => {
const items = await db.[table].findMany({ where: { id: { in: ids } } })
return ids.map(id => items.find(item => item.id === id))
})
// Server
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
user: req.user,
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`)
})
Tags
graphql
apollo
api
typescript
Tested Models
gpt-4
claude-3-5-sonnet