Apollo-client: Response Wrapper

Created on 20 Jun 2016  路  7Comments  路  Source: apollographql/apollo-client

Is there way to somehow wrap responses from graphql server? I want to know if server returned 401 or refreshed token.

Most helpful comment

For instance your network interface allows to applyMiddleware to work with request object. It would be nice if I could apply middleware to response, and have something like general error check.

networkInterface.use([{ applyMiddleware(res, next) { if (!res.status===401) { dispatch(logout()); } next(); } }]);

Therefore I wouldn't need to write same code for every query and mutation response.

All 7 comments

Can you explain a bit more what you mean by this? For example, a hypothetical code snippet of what you would like to do? I'm not quite sure what wrapping a response would mean.

For instance your network interface allows to applyMiddleware to work with request object. It would be nice if I could apply middleware to response, and have something like general error check.

networkInterface.use([{ applyMiddleware(res, next) { if (!res.status===401) { dispatch(logout()); } next(); } }]);

Therefore I wouldn't need to write same code for every query and mutation response.

@pfulop Yes! 馃檶 I was just searching the docs for a way to to this. It could be something like an afterware applicable after fetch return the result promise on networkInterface - line 142

Use cases:

  • logout user
  • remove expired tokens
  • handle errors & redirects
networkInterface.use([{
  applyAfterware(result, next) {

    if (result.status === 401) {
      logout()

      // or
      // localStorage.removeItem("token")
      // temporarilyPopupError(result.error.message)
      // redirectToSignInPage()
    }

    next()
  }
}])

Sure, would you be interested in submitting a PR for this?

@stubailo I'm a very junior developer but I can give it a try

This can be closed now since #399 is merged?

Yup, this can be closed.

Was this page helpful?
0 / 5 - 0 ratings