- Sends JSON HTTP requests from a Web Worker, so fetching and body parsing stay off the main thread.
- Singleton.
import { RequestManager } from 'ohzi-components'gives you the instance, so don't callnew.
-
init(browser): Initialize component. Creates the worker.browser: Browser fromohzi-core. Call it afterBrowser.init(). Safari requests usecache: 'no-cache', other browsers use'default'.
-
get(url, callback, error_callback): Sends aGETrequest. -
post(url, data, callback, error_callback): Sends aPOSTrequest withdataas the JSON body. -
put(url, data, callback, error_callback): Sends aPUTrequest withdataas the JSON body. -
delete(url, data, callback, error_callback): Sends aDELETErequest withdataas the JSON body. -
__request({ url, method, data, headers, with_data, callback, error_callback }): The call behind the four methods above. (private)headers: Extra headers, merged overContent-Type: application/json.with_data:falseskips reading the body, socallbackgets the status only. Defaulttrue.
Both callbacks receive (status, data):
callback: The response arrived and its status isn't 4xx.datais the parsed JSON body, or the raw text when the body isn't JSON.error_callback:- 4xx response:
statusis the response status anddatais the parsed body. - Network failure:
statusis0anddatais the error message.
- 4xx response:
A missing callback logs Request not handlered (or Error not handlered).
Every request uses mode: 'cors', credentials: 'same-origin', redirect: 'follow' and Content-Type: application/json, and sends JSON.stringify(data) as the body.
import { Browser } from 'ohzi-core';
import { RequestManager } from 'ohzi-components';
RequestManager.init(Browser);
RequestManager.get('/api/scores',
(status, data) =>
{
console.log(status, data);
},
(status, error) =>
{
console.warn('Could not load scores', status, error);
});
RequestManager.post('/api/scores', { name: 'ohzi', score: 10 }, on_saved, on_failed);- 5xx responses go to
callback, noterror_callback. Checkstatusincallback. - Callbacks are stored by URL. If two requests to the same URL are in flight, both responses go to the callbacks of the last one.
- A relative URL like
api/scoresresolves against the worker script, not the page. Use root-relative (/api/scores) or absolute URLs. - There is no timeout or abort.
- The worker is loaded from
./RequestWorker.ts, next to the module. That works when the app bundlesohzi-componentsfromsrc/, as the boilerplate's Vite alias does. The publishedbuild/index.module.mjskeeps that URL but doesn't ship the worker file.