request-container
This library is an extremely lightweight only do two things:
-
Same http requests should derive same result at the same range of time.
-
Every http requests should pass to a container so that developer could manage it anytime anywhere.
Senarios
-
For any component oriented application such as react, vue, angular, each component works independently and isolately. Therefore, if any two component dispatch same http request at around same time, mutiple same requests made. TO mitigate this, request-conatinersolves this problem to ensure all same requests are only made one and only one outgoing http request at same range of time.
-
For Single Page Applications, they make use of Html5 History Api to manage routing. However, any requests that made in previous page might be hard to manage/cancel. Imagine the performance when a user is uploading 100mb file and unpatiently leave the page, the 100mb file upload connection is still there if developer not manually terminate it. request-conatiner solves this problem to as it provide a container to preserve processing request.
Environment
NodeJS
Browser
Language
JavaScript
Typescript
How to use
What you need to do is to pass your promise request in the requestContainer and it will return you a promiseState which contains your promise as well as current promise request status (none/loading/success/error).
Javascript
; const requestContainer = RequestContainer; // const promiseState = requestContainer.put(<a key used to identify your request>, // <a function that will execute a request and return a promise>); const promiseState = requestContainer;
Typescript
; ; //type RequestParamType = {url: 'www.example.com/api', data: {token:123}, method: 'get'}; //promiseFn:() =>Promise<any>, e.g. promiseFn = ()=>$.ajax(...); ;
Concurrent Same Request
Here is a scenario for concurrent same request (for more example please check the tests folder)
; ; //assume first attempt request consumes 2 sec ; ; ; //assume second attempt request consumes 4 sec, it doesn't matter how long it takes ; ; ; /** * since they are exactly the same request, therefore if request1 sent * request2 will be intercepted and points to request1, which means request1 will share the response with request2 * the entire process therefore will have one and only one outgoing request. */
Roadmap
The request-container will be used as a small part of module in next library which is about smart http request caching. I am stuck at how to create a suitable algorithm to handle cache garbage collection (GC). Once done, it will make more sense of why request-container is simple but very useful for any request module for any project.
Unit Testing
This library has been gone through proper unit testing under the tests folder, feel free to use the request-container :)
License
MIT