Skip to content

Allow response modifications in onAfterSuccess callback #225

@prantlf

Description

@prantlf

I would like to call the server, but modify the response to include additional data, before it is consumed by the caller. It helps the development, when the server API is only partially ready or when you want to test an alternative scenario, which would be not so easy to prepare on the server. I tried the proxy option:

mockjax({
  url: '/api/currentuser',
  proxy: '/api/currentuser',
  onAfterSuccess: function (response) {
    response.image = '/images/profile
  }
});

This way "almost" works, except for:

  1. The onAfter[X] callbacks have no arguments. Was there any reason not to propagate the jQuery callback arguments 1:1 there?
  2. MVC Frameworks like Backbone.js register on success and error callbacks to update their model with the server response. If the server response needs to be modified before it reaches the model controller, the onAfter[X] have to be executed before the jQuery originals.

I demonstrate this change in the propagate-callback-arguments branch.

Thinking further, the proxy option would work only for simple scenarios, allowing only url, type and data passed to the proxy. Other options like headers or contentType may be missing. I realized, that passing the request through to the server and updating the response may need more than the proxy offers. I introduced a new passThrough option, which makes the mocking simpler:

mockjax({
  url: '/api/currentuser',
  passThrough: true,
  onAfterSuccess: function (response) {
    response.image = '/images/profile
  }
});

I demonstrate this change in the passthrough-requests branch.

I got the "half-mocking" scenario, when the server responds, but the respond needs to be "massaged" a little before passed to the caller, working using the two changes above. Would you accept them into the official mockjax? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions