可以使用数据源解析器来解决这个问题。数据源解析器是一个在GraphQL执行过程中拦截请求并检索数据的中间件。我们可以将多个数据源绑定到同一个GraphQL Schema上,并使用数据源解析器来将查询分解成多个独立的请求并将结果合并。
以下是一个示例代码,演示如何将具有不同类型的数据源(数据库和Rest API)绑定到同一个GraphQL Schema上:
const { ApolloServer, gql } = require('apollo-server');
const { RESTDataSource } = require('apollo-datasource-rest');
const { Pool } = require('pg');
const typeDefs = gql`
type Book {
id: ID!
title: String!
author: String!
}
type Query {
book(id: ID!): Book
}
`;
class BookAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://myrestapi.com/';
}
async getBook(id) {
return this.get(`book/${id}`);
}
}
const resolvers = {
Query: {
book: async (_, { id }, { dataSources }) => {
const [apiData, dbData] = await Promise.all([
dataSources.bookAPI.getBook(id),
dataSources.db
.query('SELECT * FROM books WHERE id = $1', [id])
.then((res) => res.rows[0]),
]);
return {
id,
title: apiData.title,
author: dbData.author,
};
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
bookAPI: new BookAPI(),
db: new Pool({ connectionString: 'postgres://localhost:5432/mydb' }),
}),
});
server.listen().then(({ url }) => {
console.log(`� Server ready at ${url}`);
});
在上面的示例中,我们实现了一个包含一个book查询的GraphQL Schema,并使用ApolloServer将它们绑定在一起。我们将具有