【问题标题】:How to access an ApolloServer data source outside of its constructor?如何在构造函数之外访问 ApolloServer 数据源?
【发布时间】:2020-03-16 03:22:11
【问题描述】:

我正在使用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)
      }
    }
  }
})

我的问题是我更喜欢使用类来实现解析器,所以对于 Post,我有这样的东西:

class Post {
  constructor(public id: number, public title: string, public content: string) {}

  comments() {
    return new Datasource1.getComments(this.id)
  }
}

我想知道这是否受支持? Datasource1 的多个实例可以共享同一个缓存吗?我不这么认为。 是否可以在其构造函数之外访问ApolloServerdataSources

【问题讨论】:

  • 您可以在 cmets 方法中访问 argumentscontextresolveInfocomments(arguments, context, resolveInfo) { context.datasources... }
  • 太好了,到目前为止我没有在任何文档中看到它。谢谢大佬!
  • 我可能会在这里发布一个答案,用一些更好的词来包装这个:)
  • Op 在这里讨论解析器对象。这就是问题的全部意义所在。在解析器对象中,根对象是this

标签: typescript graphql apollo-server


【解决方案1】:

因为这再次出现在评论中。 GraphQL.js 允许两种不同的方式来定义解析器。您可以使用普通数据对象并在架构内定义解析器逻辑。这就是大多数人使用 GraphQL 的方式,因为这是大多数文档显示的内容,也是 Apollo 所宣扬的内容。第二种方法是您依赖默认解析器并创建数据访问对象。让我快速展示一下我们如何想象一个字段在概念上被解析:

// When the field specifies a resolver
if (typeof fieldConfig.resolver !== 'undefined') {
  return fieldConfig.resolver(root, args, context, resolveInfo);
}
// When the field does not specify a resolver but the root value has a method with
// the same name
if (typeof root[fieldConfig.name] === 'function') {
  return root[fieldConfig.name](args, context, resolveInfo);
}
// Otherwise we return the value under the name with the potential of it being undefined
return root[fieldConfig.name];

所以我们可以返回带有方法的对象,就像 OP 对我们所有类型所做的那样。该对象包装静态属性,并具有用于需要参数或需要访问上下文的更复杂字段的方法。请注意,在这种情况下,根值是如何不传递的,因为该方法在 根值上调用。这意味着根值可以在方法内部以 this 的形式访问,就像我们在 OOP 中习惯的那样。

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

class Post {
  constructor(public id: number, public title: string, public content: string) {}

  comments(_args, { datasources }) {
    return datasources.ds1.getComments(this.id)
  }
}

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2018-02-20
    • 2016-07-16
    • 2019-07-16
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多