简体   繁体   中英

How to compose a graphQL query from a REST Api response?

I have an API response from a REST API server which I called using my REACT + Apollo with apollo-link-rest. but the response of the API looks like this

[
 [
   {
    "name": "joe"
    "address": "123 street hello city"
   },
   {
    "name": "joe2"
    "address": "1233 street2 hello2 city"
   }
 ],
 2356
]

How can I create a query with this kind of response that has an array with a number as a last item in the array and the first item of the array consist of list of users?

So far I just have this query.

const QueryTest = gql`
  query people {
    people @rest(type: "People", path: "/allpersons")
  }
`;

1st: you need name and address props within (inside) people query - 'ask for what you need' - to get results.

2nd: Work with apollo-link-rest usually needs type patching - technique used to adapt/transform existing (REST) responses to the current needs (structures). It can be combined with response transformer but this step isn't required.

Sometimes you need to add id (calculated from other fields, unique) for nested types (apollo normalizing cache requirement) or define additional 'response type' above desired/required type - google for type patching examples (fe patchDeeper usage) or tutorials... define patchers, use debugger...

It's far easier when you know what to expect/what is needed - compare responses with working graphql responses.

Had the same issue, you can use responseTransformer in your link to transform the response.

const restLink = new RestLink({
    uri: '...',
    responseTransformer: async response =>
        response.json()
              .then((data: any) => {
                if (Array.isArray(data)) return { data }
                else return data
            })
});

So you should be able to use the query like this:

const QueryTest = gql`
  query people {
    people @rest(type: "People", path: "/allpersons") {
      data
    }
  }
`;

Where data would contain:

[
 [
   {
    "name": "joe"
    "address": "123 street hello city"
   },
   {
    "name": "joe2"
    "address": "1233 street2 hello2 city"
   }
 ],
 2356
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM