Post 数据到带有请求承诺的 graphql 服务器
Post data to a graphql server with request-promise
我正在使用 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)
以上代码运行良好。但是我对如何进行突变感到困惑,因为我需要像这样指定实际突变和输入数据:
// 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 库不是为这个用例设计的?
graphql-request 库似乎做了我需要请求承诺库做的事情。
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})
使用 body
,而不是 formData
。您的 body 应包含三个属性:
query
:您要发送的 GraphQL 文档。即使操作是突变,属性 仍然是命名查询。
variables
:序列化为 JSON object 的变量值映射。仅当您的操作使用变量时才需要。
operationName
:指定要执行的操作。仅当您的文档包含多个操作时才需要。
request.post({
uri : '...',
json: true,
body: {
query: 'mutation { ... }',
variables: {
input: {
name: '...',
email: '...',
},
},
},
})
我正在使用 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)
以上代码运行良好。但是我对如何进行突变感到困惑,因为我需要像这样指定实际突变和输入数据:
// 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 库不是为这个用例设计的?
graphql-request 库似乎做了我需要请求承诺库做的事情。
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})
使用 body
,而不是 formData
。您的 body 应包含三个属性:
query
:您要发送的 GraphQL 文档。即使操作是突变,属性 仍然是命名查询。variables
:序列化为 JSON object 的变量值映射。仅当您的操作使用变量时才需要。operationName
:指定要执行的操作。仅当您的文档包含多个操作时才需要。
request.post({
uri : '...',
json: true,
body: {
query: 'mutation { ... }',
variables: {
input: {
name: '...',
email: '...',
},
},
},
})