In GraphQL, resolvers receive a context argument. What is its main purpose?
Think about what information needs to be accessible to all resolvers during a single request.
The context argument is a shared object passed to every resolver during a GraphQL request. It commonly holds authentication data, database connections, or other utilities needed by resolvers.
Given the following resolver code snippet, what will getUserName return?
const resolvers = {
Query: {
getUserName: (parent, args, context) => {
return context.user.name;
}
}
};
const context = { user: { id: 1, name: 'Alice' } };
// Query: { getUserName }Look at what context.user.name contains.
The resolver returns context.user.name, which is "Alice" in the provided context object.
Which option contains a syntax error in accessing the context argument in a resolver?
const resolvers = {
Query: {
getUserEmail: (parent, args, context) => {
return context.user.email;
}
}
};Check if the context argument is declared properly.
Option A does not declare the context parameter, but tries to use it, causing a ReferenceError.
You want to avoid opening a new database connection in every resolver. How can you use the context argument to optimize this?
Think about sharing resources efficiently during a request.
Creating one database connection in the context and reusing it in all resolvers avoids overhead and improves performance.
Consider this resolver:
const resolvers = {
Query: {
currentUser: (parent, args, context) => {
return context.userInfo;
}
}
};
// Context setup:
const context = { user: { id: 5, name: 'Bob' } };
// Query: { currentUser }Why does currentUser return null or undefined?
Compare the property names used in the resolver and the context object.
The resolver accesses context.userInfo but the context object only has a user property, so it returns undefined.