Skip to content

GraphQL Resolver Functions

Learn how to implement GraphQL resolver functions that fetch data from multiple sources like SQL databases, REST APIs, and MongoDB.

Sure, here's an example of how to use resolver functions in GraphQL:

Let's say you have a schema that defines a User type, with fields for id, name, and email. You want to fetch the data for each field from a different data source - id from a SQL database, name from a REST API, and email from a MongoDB database.

Here's how you could define resolver functions for each field:

type User {
  id: ID
  name: String
  email: String
}
 
type Query {
  user(id: ID!): User
}
 
type UserResolver {
  id: (parent, args, context) => {
    // Fetch the ID from a SQL database
    return db.query(`SELECT id FROM users WHERE id = ${args.id}`);
  },
  name: (parent, args, context) => {
    // Fetch the name from a REST API
    return fetch(`https://api.example.com/users/${parent.id}`)
      .then(res => res.json())
      .then(data => data.name);
  },
  email: (parent, args, context) => {
    // Fetch the email from a MongoDB database
    return mongo.db('users').collection('users')
      .findOne({ id: parent.id })
      .then(data => data.email);
  }
}
 
const resolvers = {
  Query: {
    user: (parent, args, context) => {
      // Call the UserResolver functions to fetch the data for each field
      return {
        id: UserResolver.id(parent, args, context),
        name: UserResolver.name(parent, args, context),
        email: UserResolver.email(parent, args, context)
      }
    }
  }
}
 
const schema = makeExecutableSchema({
  typeDefs: [typeDefs],
  resolvers: resolvers
});

In this example, we define a UserResolver object that contains resolver functions for each field in the User type. When a query is made for a User, the user resolver function is called, which in turn calls the resolver functions for each field in the UserResolver object. Each resolver function fetches the data from a different data source, and returns the result.

Note that in this example, we assume that the SQL database is available through a db object, the REST API is available through a fetch function, and the MongoDB database is available through a mongo object. In practice, you would need to replace these with the appropriate database connections for your application.

This is just a simple example, but resolver functions can be used for much more complex data fetching scenarios as well.

Tags

GraphQLresolversAPI developmentdatabase integrationbackend