0
0
GraphQLquery~5 mins

SQL database resolvers in GraphQL

Choose your learning style9 modes available
Introduction

SQL database resolvers help connect GraphQL queries to your SQL database. They get the right data when someone asks for it.

You want to get user details from a SQL database when a GraphQL query asks for it.
You need to fetch a list of products stored in a SQL database through GraphQL.
You want to update or insert data in your SQL database using GraphQL mutations.
You want to combine data from multiple SQL tables and return it via GraphQL.
You want to control exactly how GraphQL queries talk to your SQL database.
Syntax
GraphQL
const resolvers = {
  Query: {
    getItems: async (parent, args, context) => {
      const [result] = await context.db.query('SELECT * FROM items WHERE category = ?', [args.category]);
      return result;
    }
  }
};

Resolvers are functions that run when a GraphQL query or mutation is called.

They usually get arguments and use them to run SQL queries to fetch or change data.

Examples
This resolver fetches a user by ID from the SQL database when the getUser query is called.
GraphQL
const resolvers = {
  Query: {
    getUser: async (parent, args, context) => {
      const [user] = await context.db.query('SELECT * FROM users WHERE id = ?', [args.id]);
      return user;
    }
  }
};
This resolver adds a new product to the database when the addProduct mutation is called.
GraphQL
const resolvers = {
  Mutation: {
    addProduct: async (parent, args, context) => {
      await context.db.query('INSERT INTO products (name, price) VALUES (?, ?)', [args.name, args.price]);
      return { success: true };
    }
  }
};
Sample Program

This resolver gets all books by a specific author from the SQL database when the getBooks query is called.

GraphQL
const resolvers = {
  Query: {
    getBooks: async (parent, args, context) => {
      const [books] = await context.db.query('SELECT * FROM books WHERE author = ?', [args.author]);
      return books;
    }
  }
};
OutputSuccess
Important Notes

Resolvers must return data in the shape expected by the GraphQL schema.

Use parameterized queries to avoid SQL injection risks.

Resolvers can be async to handle database calls that take time.

Summary

SQL database resolvers connect GraphQL queries to your SQL data.

They run SQL commands to get or change data based on query or mutation requests.

Resolvers help keep your data fetching organized and secure.