Typescript 如何在其构造函数之外访问ApolloServer数据源?

Typescript 如何在其构造函数之外访问ApolloServer数据源?,typescript,graphql,apollo-server,Typescript,Graphql,Apollo Server,我正在使用apollo datasource rest从rest API获取数据。从文档中,您可以集成如下数据源: const server = new ApolloServer({ typeDefs, dataSources: () => ({ ds1: new Datasource1() }), resolvers: { Post: { comments: (post, _args, { dataSources }) => {

我正在使用apollo datasource rest从rest API获取数据。从文档中,您可以集成如下数据源:

const server = new ApolloServer({
  typeDefs,
  dataSources: () => ({
    ds1: new Datasource1()
  }),
  resolvers: {
    Post: {
      comments: (post, _args, { dataSources }) => {
        dataSources.ds1.getComments(post.id)
      }
    }
  }
})
class Post {
  constructor(public id: number, public title: string, public content: string) {}

  comments() {
    return new Datasource1.getComments(this.id)
  }
}
我的问题是,我更喜欢使用类来实现解析器,因此对于Post,我有如下内容:

const server = new ApolloServer({
  typeDefs,
  dataSources: () => ({
    ds1: new Datasource1()
  }),
  resolvers: {
    Post: {
      comments: (post, _args, { dataSources }) => {
        dataSources.ds1.getComments(post.id)
      }
    }
  }
})
class Post {
  constructor(public id: number, public title: string, public content: string) {}

  comments() {
    return new Datasource1.getComments(this.id)
  }
}
我想知道这是否得到支持?
Datasource1
的多个实例能否共享同一个缓存?我不这么认为。
是否可以在其构造函数之外访问ApolloServer
数据源?

,因为这又出现在一条评论中。js允许使用两种不同的方式定义解析器。要么使用普通数据对象,要么在模式内部定义解析器逻辑。这是大多数人做GraphQL的方式,因为这是大多数文献所展示的,也是阿波罗所宣扬的。第二种方法是依赖默认解析器并创建数据访问对象。让我快速演示如何从概念上解决一个字段:

//当字段指定冲突解决程序时
if(fieldConfig.resolver的类型!==“未定义”){
返回fieldConfig.resolver(根、参数、上下文、resolveInfo);
}
//当字段未指定冲突解决程序,但根值具有
//同名
if(根的类型[fieldConfig.name]=“函数”){
返回根[fieldConfig.name](参数、上下文、resolveInfo);
}
//否则,我们返回名称下的值,该值可能未定义
返回根目录[fieldConfig.name];
所以我们可以用方法返回对象,就像OP对所有类型所做的一样。对象包装静态属性,并具有用于需要参数或需要访问上下文的更复杂字段的方法。请注意,在这种情况下,由于方法是在根值上调用的,所以没有传递根值。这意味着根值可以作为方法内部的
this
访问,就像我们习惯于从OOP访问一样

直接回答这个问题:上下文可以作为解析器方法中的第二个参数访问。具体来说,我们可以编写以下代码:

class Post{
构造函数(public id:number,public title:string,public content:string){}
注释(_args,{datasources}){
返回datasources.ds1.getComments(this.id)
}
}

您可以访问comments方法中的
参数
上下文
解析信息
注释(参数、上下文、解析信息){context.datasources…}
。这太好了,到目前为止,我没有在任何文档中看到它。谢谢你,伙计!解决方案:我可能会在这里发布一个答案,用更好的话来概括:)Op在这里谈论解析器对象。这就是问题的关键所在。在解析器对象中,根对象是this