Resolver structure and context in GraphQL

From the GraphQL cheat sheet · Resolvers · verified Jul 2026

Resolver structure and context

javascript
// Resolver function signature
const resolvers = {
  Query: {
    // (parent, args, context, info) => result
    user: async (parent, args, context, info) => {
      // parent: Result from parent resolver
      // args: Arguments passed to field
      // context: Shared context (auth, db, etc.)
      // info: Query AST and execution info
      
      // Check authentication
      if (!context.user) {
        throw new Error('Not authenticated');
      }
      
      // Fetch from database
      return await context.db.user.findUnique({
        where: { id: args.id }
      });
    }
  }
};

// Context setup - context lives on the integration (Apollo Server 4+)
const server = new ApolloServer({ typeDefs, resolvers });

app.use('/graphql', cors(), express.json(), expressMiddleware(server, {
  context: async ({ req }) => {
    // Get auth token
    const token = req.headers.authorization || '';
    
    // Verify user
    const user = await verifyToken(token);
    
    // Return context object
    return {
      user,
      db: prisma,
      dataSources: {
        userAPI: new UserAPI(),
        postAPI: new PostAPI()
      },
      req,
      pubsub
    };
  },
}));
💡 Resolvers fetch data for schema fields
⚡ Four arguments: parent, args, context, info
📌 Context shares data across resolvers
🟢 Can be sync or async functions

More GraphQL tasks

Back to the full GraphQL cheat sheet