GraphQL servers need to provide data to clients. Why is it common for GraphQL servers to use databases as their data source?
Think about where data is usually stored in applications.
GraphQL servers use databases because databases hold the actual data in a structured way. GraphQL queries ask for specific data, and databases can efficiently provide that data.
Given a GraphQL query requesting user { id, name } and a database table users with columns id, name, and email, what will the query return?
query {
user {
id
name
}
}The query only asks for id and name, not email.
The GraphQL query requests only the id and name fields. The database returns those fields for each user.
Look at this resolver code snippet that fetches data from a database. What is the syntax error?
const resolvers = { Query: { user: (parent, args, context) => { return context.db.query('SELECT * FROM users WHERE id = $1', args.id) } } }
Check how parameters are passed to parameterized queries.
Database query methods usually expect parameters as an array. Passing args.id directly is incorrect syntax.
When a GraphQL query requests nested data (e.g., users and their posts), what is a common optimization to reduce database load?
Think about how to avoid many repeated database calls.
Data loader batches multiple requests into one and caches results, reducing database load and improving performance.
This GraphQL query requests a user by ID, but it returns null even though the user exists in the database. What is the likely cause?
query {
user(id: 5) {
id
name
}
}Check how the resolver uses the query arguments.
If the resolver ignores or misuses the 'id' argument, the database query will not find the user, returning null.