0
0
GraphQLquery~5 mins

Data source integration in GraphQL

Choose your learning style9 modes available
Introduction

Data source integration helps you connect GraphQL to different places where data lives. This way, you can ask for data from many sources in one simple way.

You want to get user info from a database and product info from another service.
You need to combine data from an API and a local database in one query.
You want to fetch data from multiple places but show it together in your app.
You want to keep your data sources separate but still use GraphQL to get data.
You want to add a new data source without changing your whole app.
Syntax
GraphQL
type Query {
  fieldName: ReturnType
}

const resolvers = {
  Query: {
    fieldName: (parent, args, context, info) => {
      // fetch data from data source here
      return data;
    }
  }
};
Resolvers are functions that tell GraphQL how to get data from each source.
You can connect to databases, REST APIs, or other services inside resolvers.
Examples
This example shows how to get a user by ID from a database inside a resolver.
GraphQL
type Query {
  getUser(id: ID!): User
}

const resolvers = {
  Query: {
    getUser: (parent, args, context) => {
      return database.getUserById(args.id);
    }
  }
};
This example fetches weather data from an external API using a resolver.
GraphQL
type Query {
  getWeather(city: String!): Weather
}

const resolvers = {
  Query: {
    getWeather: async (parent, args) => {
      const response = await fetch(`https://api.weather.com/${args.city}`);
      return response.json();
    }
  }
};
Sample Program

This GraphQL schema and resolver connect to a simple data source (an array) to get a book by its ID.

GraphQL
type Query {
  book(id: ID!): Book
}

type Book {
  id: ID!
  title: String
  author: String
}

const books = [
  { id: "1", title: "1984", author: "George Orwell" },
  { id: "2", title: "The Hobbit", author: "J.R.R. Tolkien" }
];

const resolvers = {
  Query: {
    book: (parent, args) => {
      return books.find(book => book.id === args.id);
    }
  }
};
OutputSuccess
Important Notes

Resolvers can be async to handle data from APIs or databases.

Keep data sources separate to make your code easier to manage.

Test your resolvers to make sure they return the right data.

Summary

Data source integration connects GraphQL to where your data lives.

Resolvers fetch data from databases, APIs, or other services.

This lets you get data from many places with one simple query.