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.
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.
type Query {
fieldName: ReturnType
}
const resolvers = {
Query: {
fieldName: (parent, args, context, info) => {
// fetch data from data source here
return data;
}
}
};type Query {
getUser(id: ID!): User
}
const resolvers = {
Query: {
getUser: (parent, args, context) => {
return database.getUserById(args.id);
}
}
};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();
}
}
};This GraphQL schema and resolver connect to a simple data source (an array) to get a book by its ID.
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);
}
}
};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.
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.
const resolvers = {
Query: {
users: async () => {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
return data;
}
}
};const resolvers = {
Query: {
products: () => {
const data = db.query('SELECT * FROM products');
return data;
}
}
};const resolvers = {
Query: {
combinedData: async () => {
const apiData = await fetch('https://api.example.com/items').then(res => res.json());
const dbData = await db.query('SELECT * FROM items');
// What next?
}
}
};Pass the test and this pattern moves unknown