Каков правильный синтаксис для передачи переменной в мутацию в graphql? - PullRequest
0 голосов
/ 18 февраля 2019

У меня есть собственное приложение реакции.

Какой правильный синтаксис в 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);
})

1 Ответ

0 голосов
/ 18 февраля 2019

Чтобы передать переменные в мутацию, можно сделать что-то вроде:

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 должен соответствовать типу CustomerCreateInput.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...