@oh-my-pi/pi-utils 13.9.6 → 13.9.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/hook-fetch.ts +30 -0
- package/src/index.ts +1 -0
package/package.json
CHANGED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Intercept `globalThis.fetch` with a middleware-style handler.
|
|
3
|
+
*
|
|
4
|
+
* Returns a `Disposable` so callers can use `using` for automatic cleanup:
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* using _hook = hookFetch((input, init, next) => {
|
|
8
|
+
* if (shouldIntercept(input)) {
|
|
9
|
+
* return new Response("mocked");
|
|
10
|
+
* }
|
|
11
|
+
* return next(input, init);
|
|
12
|
+
* });
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export type FetchHandler = (
|
|
16
|
+
input: string | URL | Request,
|
|
17
|
+
init: RequestInit | undefined,
|
|
18
|
+
next: typeof fetch,
|
|
19
|
+
) => Response | Promise<Response>;
|
|
20
|
+
|
|
21
|
+
export function hookFetch(handler: FetchHandler): Disposable {
|
|
22
|
+
const original = globalThis.fetch;
|
|
23
|
+
globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) =>
|
|
24
|
+
handler(input, init, original)) as typeof fetch;
|
|
25
|
+
return {
|
|
26
|
+
[Symbol.dispose]() {
|
|
27
|
+
globalThis.fetch = original;
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|