【问题标题】:Post data to a graphql server with request-promise使用 request-promise 将数据发布到 graphql 服务器
【发布时间】:2020-05-12 06:16:41
【问题描述】:

我正在使用request-promise 库向graphql 服务器发出http 请求。为了实现查询,我这样做:

const query = `
    {
    user(id:"123173361311") {
      _id
      name
      email
    }
  }
`

const options = {
  uri: "http://localhost:5000/graphql",
  qs: { query },
  json: true
}

return await request(options)

上面的代码工作正常。但是我对如何进行突变感到困惑,因为我需要像这样指定实际的突变和 inputData:

// Input
{
   name: "lomse"
   email: "lomse@lomse.com"
}

const mutation = `
   mutation addUser($input: AddUserInput!){
      addUser(input: $input) {
          _id
          name
          email
      }
   }
`

const option = {
    uri: "http://localhost:5000/graphql",
    formData: {mutation},
    json: true,
    // how to pass the actual data input
}

request.post(option)

或者request-promise 库不是为这个用例设计的?

【问题讨论】:

  • 查询也可以包含变量...在某些 graphiql 游乐场中检查浏览器网络请求以获取详细信息
  • 有趣的是,网络选项卡没有记录任何突变请求
  • 可以使用socket通信
  • 搜索post mutation, f.e. stackoverflow.com/a/51636430/6124657
  • 这项研究展示了如何从前端执行突变,这不是我想要完成的。就我而言,我有两台服务器需要相互通信

标签: graphql request-promise


【解决方案1】:

使用body,而不是formData。你的身体应该包含三个属性:

  • query:您发送的 GraphQL 文档。即使操作是突变,该属性仍然命名为查询。
  • variables:您的变量值的映射序列化为 JSON 对象。仅当您的操作使用变量时才需要。
  • operationName:指定要执行的操作。仅当您的文档包含多项操作时才需要。
request.post({
  uri : '...',
  json: true,
  body: {
    query: 'mutation { ... }',
    variables: {
      input: {
        name: '...',
        email: '...',
      },
    },
  },
})

【讨论】:

  • 太棒了!正是我想要的。他们的文档中是否提到了这一点?您是从哪里获得这些信息的?
  • 由于 GraphQL 与传输无关,spec 本身并没有指定应该如何处理 HTTP 请求。以上大多只是惯例。官网does mention it though.
  • 我一定错过了。再次感谢
【解决方案2】:

graphql-request 库似乎做了我需要 request-promise 库做的事情。

import { request } from 'graphql-request'

const variables = {
   name: "lomse",
   email: "lomse@lomse.com"
}

const mutation = `
   mutation addUser($input: AddUserInput!){
      addUser(input: $input) {
          _id
          name
          email
      }
   }
`

response = await request(uri, mutation, {input: variables})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-08
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多