This approach has some really cool benefits:
- The API class stays as a small and clean unit
- Easy to use other caching techniques. Even multiple are supported simultaneously
- Explicit code
Another cool thing is to explicitly pass your client (HTTP, WebSocket, database, etc) as an argument to the constructor of your API:
const api = new MyApi(new HttpClient());
const api = new InMemoryApiCacheDecorator(
new MyApi(new HttpClient());
);
api.get('/myresource/1').then(...);
Our HttpClient already returns a CancellablePromiseRequest. It is a wrapper over jQuery.ajax promises:
var myRequest = api.get('/myresource/1').then(...);
myRequest.cancel(); // it throws Promise.CancellationError