Apollo Server:dataSources与上下文结合使用以与数据库一起使用

opo*_*nil 7 apollo-server

看完本文档后,我不确定是否要像其他时候一样使用简单的上下文,或者最好使用dataSources处理数据库。

DataSource是与数据库通信的正确方法,还是最好仅将其与REST API进行通信?

基本上,在这种情况下使用dataSources和context有什么好处吗?

log*_*kal 0

如果您查看您指出的文档。您可以在初始化 Apollo Server 时添加数据源,如下所示:

const server = new ApolloServer({
  typeDefs,
  dataSources: () => ({
    launchAPI: new LaunchAPI(),
    userAPI: new UserAPI({ store })
  })
});
Run Code Online (Sandbox Code Playgroud)

正是因为这个数据源成为上下文的一部分。如果您还记得您对上下文进行了解构以公开数据源,如下所示

module.exports = {
  Query: {
    launches: (_, __, { dataSources }) =>
      dataSources.launchAPI.getAllLaunches(),
    launch: (_, { id }, { dataSources }) =>
      dataSources.launchAPI.getLaunchById({ launchId: id }),
    me: (_, __, { dataSources }) => dataSources.userAPI.findOrCreateUser()
  }
};
Run Code Online (Sandbox Code Playgroud)

如果您想访问数据源的实例,例如 UserAPI 或 LaunchAPI,则必须使用dataSources.userAPI