【问题标题】:GraphQL resolvers contained within a node process rather than a server?GraphQL 解析器包含在节点进程而不是服务器中?
【发布时间】:2019-10-05 23:17:10
【问题描述】:

我需要创建类似于 GraphQL 服务器但完全包含在节点进程而不是实际服务器中的东西。因此,本质上是一个 JavaScript 函数,您可以将查询或突变作为字符串调用,它会根据您的解析器返回一个带有响应的对象或字符串。

我知道这是一个奇怪的要求。我们需要在我的公司模拟一个 GraphQL 服务器,由于我们构建管道的一些限制,我们无法运行实际的服务器。

抱歉,这是一个非常开放的问题,但我不知道从哪里开始。哪个包包含 GraphQL 的核心功能?如果我正在制作 GraphQL 服务器,我会使用 Apollo Server 或 GraphQL Yoga 包,但很难通过谷歌搜索我需要什么,因为这是一个不寻常的要求。

【问题讨论】:

    标签: node.js graphql


    【解决方案1】:

    您只需要原版 GraphQL.js 包 (graphql) 即可针对模式执行查询。该包导出具有以下签名的graphql 函数:

    graphql(
      schema: GraphQLSchema,
      requestString: string,
      rootValue?: ?any,
      contextValue?: ?any,
      variableValues?: ?{[key: string]: any},
      operationName?: ?string
    ): Promise<GraphQLResult>
    

    来自文档:

    graphql 函数对 GraphQL 请求进行词法分析、解析、验证和执行。它需要一个模式和一个请求字符串。可选参数包括 rootValue,它将作为根值传递给 executor,contextValue,它将传递给所有解析函数,variableValues,它将传递给 executor 为 requestString 中的任何变量提供值,以及 operationName ,它允许调用者指定 requestString 中的哪个操作将在 requestString 包含多个顶级操作的情况下运行。

    所以给定一个模式,你可以这样做:

    const request = `
      query MyQuery {
        someField
      }
    `
    const { data, errors } = graphql(schema, request)
    

    注意:如果您有 typeDefsresolvers,通常会传递给 ApolloServer 配置,则可以通过将它们传递给 graphql-tools' makeExecutableSchema 来创建 GraphQLSchema 对象(这就是apollo-servergraphql-yoga 在后台使用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-15
      • 2018-05-13
      • 2021-08-22
      • 1970-01-01
      • 2017-10-23
      • 2018-01-05
      • 2019-03-21
      • 2020-04-26
      相关资源
      最近更新 更多