首页 > 解决方案 > 在graphql中将变量传递给突变的正确语法是什么

问题描述

我有一个反应原生应用程序。

graphql 中将变量传递给customerCreate的正确语法是什么?

const url = 'https://xxxx.myshopify.com/api/graphql';
const query = `
    var variable = {
          "input": {
          "email": "test@test.com",
          "password": "pass"
          }
    }

    mutation customerCreate($input: CustomerCreateInput!) {
      customerCreate(input: $input) {
        userErrors {
          field
          message
        }
        customer {
          id
        }
      }
    }
`;
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: query }),
})
.then(res => res.json())
.then(res => console.log(res.data));
.catch(err => {
    console.log('-- gql err --')
    console.error(err);
})

标签: react-nativegraphql

解决方案


将变量传递给突变的一种方法可能是执行以下操作:

const url = 'https://xxxx.myshopify.com/api/graphql';
const query = `
    mutation customerCreate($input: CustomerCreateInput!) {
      customerCreate(input: $input) {
        userErrors {
          field
          message
        }
        customer {
          id
        }
      }
    }
`;
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 
        query: query,
        variables: {
           input: {
             email: "test@test.com",
             password: "pass"
           }
        }, 
    }),
})
.then(res => res.json())
.then(res => console.log(res.data));
.catch(err => {
    console.log('-- gql err --')
    console.error(err);
})

并且只要确保variables里面的对象JSON.stringify必须匹配 type CustomerCreateInput


推荐阅读