mlegenhausen / fetch-intercept

Interceptor library for the native fetch command inspired by angular http intercepts.
MIT License
406 stars 52 forks source link

Add ability to limit fetch interception to a specific component only #28

Closed ghost closed 6 years ago

ghost commented 6 years ago

My scenario is this: on a single page I have multiple independent components that use the fetch API. All of them require to mutate requests (add request headers, etc.) and handle the response, so they all register an interceptor. The issue here is that a fetch request from one component is intercepted by all other components interceptors. Does anyone have an idea how to ensure that a fetch request originating from one component is intercepted only by an interceptor registered by the same component? In older versions of JS there was something like arguments.caller, so it was possible to identify where the function call originated, but this is deprecated now and not available in "use strict" mode.

mlegenhausen commented 6 years ago

@aluczak this will only work for the request interceptor but you can extend your fetch config object by a component key. This key should be available in your request interceptor, so you can check from which component the request was made. This does not work with requestError, response or responseError.

We could extend the call signature of requestError, response or responseError to forward the arguments given to the fetch call. So you could use the same trick as with the request interceptor. Feel free to provide a pull request.

ghost commented 6 years ago

@mlegenhausen By extending the fetch config do you mean to add an additional property to the FetchInterceptor interface?

mlegenhausen commented 6 years ago
fetch('some url', {
  component: 'test'
});
ghost commented 6 years ago

That would work fine if the fetch requests would be made always by our custom code. But we also use 3rd party components, such as Microsoft Graph API, that send fetch requets behind the scenes and we can't pass any additional parameters.

mlegenhausen commented 6 years ago

It seems what you need is to define zones in which async code execution can be tracked. You could try CLS or zone.js

ghost commented 6 years ago

@mlegenhausen - thank you. I'll try this. Basically, instead of repeating the same code to handle fetch errors in all components on the page, we are trying to write a React HOC to do the job in one place. Does not seem to be that straightforward as it appeared.