question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't modify response with afterware

See original GitHub issue

I am trying to modify response data following this guide https://github.com/apollographql/apollo-client/blob/master/Upgrade.md#afterware-data-manipulation

Apollo client config

//@flow
import ApolloClient from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'

const httpLink = new HttpLink({ uri: "https://swapi.apis.guru" })
const addStatusLink = new ApolloLink((operation, forward) => {
  return forward(operation).map((response) => {
    response.data.status = 'SUCCESS'
    console.log('afterware', JSON.stringify(response))
    return response;
  })
})

const link = addStatusLink.concat(httpLink)

const cache = new InMemoryCache()

export const apolloClient = new ApolloClient({
  link,
  cache: cache.restore(window.__APOLLO_STATE__),
})

saga

//@flow
import { takeEvery } from 'redux-saga'
import { SAGA_GET_STAR_WARS } from '~/app/reducers/Saga'
import { getLuke } from '~/app/api/StarWars'
import { apolloClient } from '~/app/Apollo'

export function* perform(_a: Object): Generator<*, *, *> {
  const response = yield apolloClient.query({
    query: getLuke,
    variables: {id: 'cGVvcGxlOjE='}
  })
  console.log('saga', JSON.stringify(response))
}

export function* watch(): Generator<*, *, *> {
  yield* takeEvery(SAGA_GET_STAR_WARS, perform)
}

export default watch

console:

afterware {"data":{"person":{"name":"Luke Skywalker","__typename":"Person"},"status":"SUCCESS"}}

saga {"data":{"person":{"name":"Luke Skywalker","__typename":"Person"}},"loading":false,"networkStatus":7,"stale":false}

problem: status key is present in afterware but absent in saga

minimal example to reproduce https://github.com/beornborn/apollo-client-2-response-issue

Version

  • apollo-client@2.0.0-rc.7

How can I pass custom data in response?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:26 (3 by maintainers)

github_iconTop GitHub Comments

13reactions
cy6eriacommented, Jun 28, 2019

I think I have found a solution for this problem. At first, you have to define a local scheme. You can read more about it here.

For the provided case it should looks like this:

new ApolloClient({
  link: addStatusLink.concat(authLink.concat(link)),
  cache,
  typeDefs: gql`
    type LocalStatus {
      id: String!
      success: String!
    }
  `,
  resolvers,
});

Then you have to modify your query:

const yourQuery = gql`
    query someQueryWithStatus {
        someRealDataQuery {
            id
            name
        }
        status @client {
            id
            success   
        }
    }
`;

Finally, you have to modify your transformations:

const addStatusLink = new ApolloLink((operation, forward) => {
  return forward(operation).map((response) => {
    response.data.status = {
      id: 1,
      success: 'SUCCESS',
      __typename: 'LocalStatus',
    };

    return response;
  })
})

I tried this, it works for me with latest versions of packages:

"apollo-cache-inmemory": "^1.6.2",
"apollo-client": "^2.6.3",
"apollo-link": "^1.2.12",

Hope It’ll help someone. I spent hours for this solution 🤓

6reactions
efokencommented, Jan 30, 2019

Any progress on this?

I’m having the same issue here when using cache. I wanna handle pagination with the WooCommerce REST API like so:

const authRestLink = new ApolloLink((operation, forward) => {
  operation.setContext(({ headers }) => ({
    headers: {
      ...headers,
      authorization: `Basic ${btoa(`${CLIENT_KEY}:${SECRET_KEY}`)}`,
    },
  }));
  return forward(operation).map((result) => {
    const { restResponses } = operation.getContext();
    const wpRestResponse = restResponses.find(res => res.headers.has('x-wp-total'));

    if (wpRestResponse) {
      result.data.headers = {
        xWpTotal: wpRestResponse.headers.get('x-wp-total'),
        xWpTotalpages: wpRestResponse.headers.get('x-wp-totalpages'),
      };
    }
    return result;
  });
});

When I use no-cache as fetch policy, it works fine. Otherwise the data.headers key gets stripped out.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Can't transform/normalize/modify response of GraphQL query
With REST API, I just create a middleware that normalizes the message. Ideally, ApolloClient should provide a middleware mechanism where I could ...
Read more >
Advanced HTTP networking - Apollo GraphQL Docs
Modifying response data. You can create a custom link that edits or removes fields from response.data . To do so, you call map...
Read more >
db.collection.update() — MongoDB Manual
By default, the db.collection.update() method updates a single document. ... set to the value returned by the expression, and cannot be changed afterwards....
Read more >
Unable to edit any pages in Confluence due to Collaborative ...
Navigate to Confluence Administration > General Configuration > Collaborative Editing and click on "Restart Synchrony". Afterward, try to create ...
Read more >
Interceptors | NestJS - A progressive Node.js framework
And once the response stream is received via the Observable , additional ... Let's create the TransformInterceptor , which will modify each response...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found