gpt4 book ai didi

apollo-server - Apollo 服务器 : dataSources vs context to use it with database

转载 作者:行者123 更新时间:2023-12-04 12:56:45 24 4
gpt4 key购买 nike

看到这个后documentation我不确定是否像其他时候那样使用简单的上下文,或者使用 dataSources 来处理数据库是否更好。

DataSource 是与数据库通信的正确方法,还是仅用于与 REST API 通信更好?

基本上,在这种情况下使用数据源与上下文有什么优势吗?

最佳答案

我认为最好使用 DataSource(顾名思义),并且在其上添加缓存层可能很容易。您可以创建一个 DBDataSource扩展 DataSource 的类类,因为 Apollo 不提供任何 DBDataSource类(class)。
DataSource class 是一个通用的 Apollo 数据源类,而 RESTDataSource负责从 REST API 获取数据的类。

因此,要从其余 API 中获取数据,最好使用 RESTDataSource .

Build a custom data source

Apollo doesn't have support for a SQL data source yet (although we'd love to help guide you if you're interested in contributing), so we will need to create a custom data source for our database by extending the generic Apollo data source class. You can create your own with the apollo-datasource package.

Here are some of the core concepts for creating your own data source:

  1. The initialize method: You'll need to implement this method if you want to pass in any configuration options to your class. Here, we're using this method to access our graph API's context.
  2. this.context: A graph API's context is an object that's shared among every resolver in a GraphQL request. We're going to explain this in more detail in the next section. Right now, all you need to know is that the context is useful for storing user information.
  3. Caching: While the REST data source comes with its own built-in cache, the generic data source does not. You can use our cache primitives to build your own, however!

关于apollo-server - Apollo 服务器 : dataSources vs context to use it with database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com