不同的数据源如何解析GraphQL查询?
创始人
2025-01-08 19:00:26
0

可以使用数据源解析器来解决这个问题。数据源解析器是一个在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将它们绑定在一起。我们将具有

相关内容

热门资讯

透视ai代打!wepoker公... 透视ai代打!wepoker公共底牌,wepoker养号规律,2025新版总结(有挂规律)所有人都在...
透视透视挂!wepoker国外... 透视透视挂!wepoker国外版透视,wepoker有没有挂(透视)攻略教程(有挂解密)1、每一步都...
透视安卓版!wepoker辅助... 透视安卓版!wepoker辅助器免费,we poker辅助器下载,技巧教程(有挂详情)1、上手简单,...
透视能赢!WePoKer辅助器... 透视能赢!WePoKer辅助器,wepoker透视脚本免费下载pc(透视)技巧教程(有挂解密)1)w...
透视透视!aapoker透视脚... 透视透视!aapoker透视脚本,hhpoker辅助器视频,必赢方法(有挂攻略)透视透视!aapok...
辅助透视!wepoker辅助器... 辅助透视!wepoker辅助器免费,wepoker黑侠辅助器(透视)安装教程(有挂细节)1、这是跨平...
透视透视!wepoker透视器... 透视透视!wepoker透视器免费,wepoker提高好牌率,详细教程(有挂方法)1、很好的工具软件...
透视了解!wepoker私人局... 透视了解!wepoker私人局透视插件,黑侠破解wepoker(透视)透牌教程(有挂揭秘)1、透视了...
透视科技!哈糖大菠萝助手,po... 透视科技!哈糖大菠萝助手,poker master辅助,2025教程(有挂方法)1、哈糖大菠萝助手a...
透视安装!wepoker脚本下... 透视安装!wepoker脚本下载,如何下载wepoker安装包(透视)教你教程(有挂插件);1、如何...