создание схемы graphql для ответа от API, который имеет массив объектов - PullRequest
0 голосов
/ 27 февраля 2020

Я получаю ответ от API, который выглядит следующим образом:

property: Array(100)
0: {identifier: {…}, address: {…}, location: {…}, vintage: {…}}
1: {identifier: {…}, address: {…}, location: {…}, vintage: {…}}
2: {identifier: {…}, address: {…}, location: {…}, vintage: {…}}
3: {identifier: {…}, address: {…}, location: {…}, vintage: {…}}

Мне нужен список некоторых указанных полей в объекте адреса, например, только страна и oneLine, но для каждого индекса свойство

массив

address:
country: "US"
countrySubd: "CA"
line1: "1702 ELKHORN RD"
line2: "ROYAL OAKS, CA 95076"
locality: "Royal Oaks"
matchCode: "ExaStr"
oneLine: "1702 ELKHORN RD, ROYAL OAKS, CA 95076"
postal1: "95076"
postal2: "9218"
postal3: "R002"

В течение двух дней я боролся за то, как написать схему для этого на моей странице схемы graphql. Может кто-нибудь, пожалуйста, помогите мне?

вот что я пытался, но продолжаю получать нулевое значение для данных

require("es6-promise").polyfill();
require("isomorphic-fetch");

const {
  GraphQLString,
  GraphQLList,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLInt
} = require("graphql");



const Identifier = new GraphQLObjectType({
  name: "identifier",
  fields: () => ({
    obPropId: { type: GraphQLInt }
  })
});

const AddressType = new GraphQLObjectType({
    name: 'Address',
    fields: () => ({
        country: { type: GraphQLString },
        oneLine: {type: GraphQLString }

    })
})

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    property: {
      type: new GraphQLList(Identifier),
      resolve(parent, args) {
        return fetch(
          "https://api.gateway.attomdata.com/propertyapi/v1.0.0/property/address?postalcode=95076&page=1&pagesize=100",
          {
            headers: {
              Accept: "application/json",
              APIKey: "XXXXXXXXXXXXXXXXXXXX"
            }
          }
        )
          .then((response) => { 
            const jsonResponse = response.json();
            return jsonResponse
          }).then((jsonResonse) => console.log(JSON.stringify(jsonResonse)))
          .then(res => res.data)
          .catch(error => {
            console.log(error);
          });
      }
    }
  }
});

module.exports = new GraphQLSchema({
  query: RootQuery
});

Im running it on a express server and do my checks on localhost:5000/graphql


1 Ответ

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

В комментариях нам удалось выработать следующее:

Другой тип требуется для соединения типа Адрес с типом RootQuery . Мы можем ввести тип и настроить тип возврата типа запроса:

type Property {
  id: Identifier
  address: Address
}

type Query {
  property: [Property] # consider using plural field name "properties"
}

Я создал работающий Codesandboy, чтобы показать, как он ведет себя.

...