How to Connect GraphQL Resolver to Database Easily
To connect a
GraphQL resolver to a database, import your database client inside the resolver file and use it to fetch or modify data. The resolver function receives arguments and context, where you can access the database client to run queries and return results.Syntax
A GraphQL resolver is a function that handles a specific field in your schema. To connect it to a database, you typically:
- Import or access the database client (like Prisma, Mongoose, or a SQL client).
- Use the resolver function parameters:
parent,args, andcontext. - Run database queries inside the resolver using
argsfor input andcontextfor shared resources like the database client. - Return the data fetched or modified from the database.
javascript
const resolvers = { Query: { getItem: async (parent, args, context) => { // Use context.db to query the database return await context.db.findItemById(args.id); } } };
Example
This example shows a simple GraphQL resolver connected to a mock database client. The resolver fetches an item by its ID.
javascript
const { ApolloServer, gql } = require('apollo-server'); // Mock database client const db = { items: [{ id: '1', name: 'Apple' }, { id: '2', name: 'Banana' }], findItemById: function(id) { return this.items.find(item => item.id === id); } }; // GraphQL schema const typeDefs = gql` type Item { id: ID! name: String! } type Query { getItem(id: ID!): Item } `; // Resolvers const resolvers = { Query: { getItem: (parent, args, context) => { return context.db.findItemById(args.id); } } }; // Apollo Server setup const server = new ApolloServer({ typeDefs, resolvers, context: () => ({ db }) // pass db client in context }); // Start server server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Output
Server ready at http://localhost:4000/
Common Pitfalls
Common mistakes when connecting resolvers to databases include:
- Not passing the database client in the
context, making it unavailable in resolvers. - Using synchronous database calls instead of async/await, causing unresolved promises.
- Ignoring error handling for database queries, which can crash the server.
- Directly importing database clients inside resolvers instead of using
context, reducing flexibility.
javascript
/* Wrong way: importing DB client directly inside resolver */ const db = require('./dbClient'); const resolvers = { Query: { getItem: (parent, args) => { // This can cause issues if dbClient needs context or connection setup return db.findItemById(args.id); } } }; /* Right way: pass DB client via context */ const resolversCorrect = { Query: { getItem: async (parent, args, context) => { return await context.db.findItemById(args.id); } } };
Quick Reference
Tips for connecting resolvers to databases:
- Always pass your database client through the
contextobject. - Use async/await to handle asynchronous database calls.
- Validate and sanitize
argsbefore querying the database. - Handle errors gracefully inside resolvers.
- Keep resolvers focused on data fetching and business logic only.
Key Takeaways
Pass your database client through the GraphQL context to access it in resolvers.
Use async/await in resolvers to handle asynchronous database queries properly.
Avoid importing database clients directly inside resolvers to keep code flexible.
Always handle errors in resolvers to prevent server crashes.
Validate input arguments before using them in database queries.