In GraphQL, what is the main role of the context object during query execution?
Think about what data resolvers need to share during a single request.
The context object is created per request and holds shared data like user authentication, database connections, or loaders. This allows resolvers to access common info without passing it explicitly.
Given this resolver snippet, what will be the value of userId?
const resolvers = {
Query: {
currentUser: (parent, args, context) => {
return context.userId;
}
}
};
// Context setup:
const context = { userId: 42 };Look at what the context object contains and what the resolver returns.
The resolver returns context.userId. Since the context object has userId: 42, the output is 42.
Which option contains a syntax error in setting up the GraphQL context function?
const server = new ApolloServer({
typeDefs,
resolvers,
context: ???
});The context option expects a function, not a plain object.
Option A provides a plain object instead of a function. The context option must be a function returning the context object, so D causes a syntax or runtime error.
You want to add a database connection to the context for each request. Which approach is best to avoid performance issues?
Think about connection overhead and sharing resources safely.
Creating a new connection per request (C) is expensive. Reusing a global connection (B) can cause concurrency issues. Creating once and reusing (A) balances performance and safety. Creating in resolvers (D) is inefficient.
You set up context as context: () => ({ user: null }). But in resolvers, context.user is always undefined. What is the cause?
Check how the resolver accesses context.
If the resolver does not include the context parameter, it cannot access context data, so context.user is undefined. The context function setup is correct.