Как вы форматируете свое тело в запросе выборки для мутации GraphQL? - PullRequest
0 голосов
/ 31 марта 2020

Я пробую GraphQL впервые и пытаюсь POST некоторых данных и создать новый документ в базе данных MongoDB.

Я определил модель "Office". Вот как выглядит документ:

{
  fax: 4161234567,
  image: {
    full: 'http://placehold.it/1400x800',
    large: 'http://placehold.it/1000x600',
    medium: 'http://placehold.it/700x400',
    small: 'http://placehold.it/400x200'
  },
  location: {
    address: '123 Street Name',
    city: 'Toronto',
    country: 'Canada',
    countryCode: 'CA',
    state: 'ON',
    suite: null,
    zip: 'H6L 1C8'
  },
  phone: 4161234567,
  slug: 'office-name',
  title: 'Office Name' 
}

Я использую Node и Express на сервере. Вот моя мутация:

const schema = buildSchema(`
  type Image {
    full: String
    large: String
    medium: String
    small: String
  }

  type Location {
    address: String
    city: String
    country: String
    countryCode: String
    state: String
    suite: String
    zip: String
  }

  input ImageInput {
    full: String
    large: String
    medium: String
    small: String
  }

  input LocationInput {
    address: String
    city: String
    country: String
    countryCode: String
    state: String
    suite: String
    zip: String
  }

  type Office {
    _id: String
    fax: Float
    image: Image
    location: Location
    phone: Float
    slug: String
    title: String
  }

  type Mutation {
    createOffice(fax: Float, image: ImageInput, location: LocationInput, phone: Float, slug: String, title: String): Office
  }
`);

На стороне клиента, у меня есть это:

fetch('http://localhost:4300/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    query: 'mutation { createOffice(fax: 5041234567, image: {full: "http://placehold.it/1400x800", large: "http://placehold.it/1000x600", medium: "http://placehold.it/700x400", small: "http://placehold.it/400x200"}, location: {address: "456 Wilcox Ave.", city: "Montreal", country: "Canada", countryCode: "CA", state: "QC", suite: 2300, zip: "H3A 0A8"}, phone: 5047654321, slug: "my-office", title: "My Office" { phone }  }'
  }),
})
.then((res) => {
  return res.json();
})
.then((res) => {
  console.log(res.data);
});

Я получаю эти ошибки:

Syntax Error: Expected Name, found {"

Я предполагаю, что это проблема с моим синтаксисом здесь:

body: JSON.stringify({
  query: 'mutation { createOffice(fax: 5041234567, image: {full: "http://placehold.it/1400x800", large: "http://placehold.it/1000x600", medium: "http://placehold.it/700x400", small: "http://placehold.it/400x200"}, location: {address: "456 Wilcox Ave.", city: "Montreal", country: "Canada", countryCode: "CA", state: "QC", suite: 2300, zip: "H3A 0A8"}, phone: 5047654321, slug: "my-office", title: "My Office" { phone }  }'
})

Что я делаю не так?

1 Ответ

0 голосов
/ 31 марта 2020

Вам не хватает закрывающей скобки после «My Office», чтобы указать конец списка аргументов.

Предполагается, что вы используете apollo-server, express-graphql или аналогичную библиотеку для вашего HTTP-сервера. , у вас должен быть открыт интерфейс Graph i QL или GraphQL Playground, который вы можете использовать для тестирования ваших запросов. Если нет, вы также можете использовать автономный клиент. В любом случае у вас будет возможность написать и протестировать свои запросы в редакторе, в котором есть автозаполнение и подсветка синтаксиса, что упрощает обнаружение таких синтаксических ошибок.

Вы также можете найти полезным использовать литералы шаблона при написании запросов во внешнем интерфейсе, чтобы избежать необходимости помещать все в одну строку.

...