@routar/fetch 0.1.0
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/LICENSE +21 -0
- package/README.md +11 -0
- package/dist/index.cjs +44 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +61 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +41 -0
- package/dist/index.js.map +1 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Kyungbae Min
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# @routar/fetch
|
|
2
|
+
|
|
3
|
+
Fetch-based executor for [routar](https://github.com/kbmin1129/routar) — transport adapter using the native `fetch` API.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @routar/core @routar/fetch
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
See the [main README](https://github.com/kbmin1129/routar) for full documentation.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@routar/core');
|
|
4
|
+
|
|
5
|
+
// src/create-fetch-executor.ts
|
|
6
|
+
function createFetchExecutor(baseURL, options) {
|
|
7
|
+
return core.createExecutor(async ({ method, url, params, body, headers, signal }) => {
|
|
8
|
+
const fullURL = new URL(url, baseURL);
|
|
9
|
+
if (params) {
|
|
10
|
+
core.serializeParams(params).forEach((v, k) => fullURL.searchParams.set(k, v));
|
|
11
|
+
}
|
|
12
|
+
const defaultHeaders = await options?.defaultHeaders?.() ?? {};
|
|
13
|
+
const res = await fetch(fullURL.toString(), {
|
|
14
|
+
method,
|
|
15
|
+
headers: {
|
|
16
|
+
...body != null ? { "Content-Type": "application/json" } : {},
|
|
17
|
+
...defaultHeaders,
|
|
18
|
+
...headers
|
|
19
|
+
},
|
|
20
|
+
body: body != null ? JSON.stringify(body) : void 0,
|
|
21
|
+
signal
|
|
22
|
+
});
|
|
23
|
+
if (!res.ok) {
|
|
24
|
+
throw new HttpError(res.status, res.statusText);
|
|
25
|
+
}
|
|
26
|
+
if (res.status === 204 || res.headers.get("content-length") === "0") {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
return res.json();
|
|
30
|
+
}, options?.middlewares);
|
|
31
|
+
}
|
|
32
|
+
var HttpError = class extends Error {
|
|
33
|
+
constructor(status, statusText) {
|
|
34
|
+
super(`HTTP ${status}: ${statusText}`);
|
|
35
|
+
this.status = status;
|
|
36
|
+
this.statusText = statusText;
|
|
37
|
+
this.name = "HttpError";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
exports.HttpError = HttpError;
|
|
42
|
+
exports.createFetchExecutor = createFetchExecutor;
|
|
43
|
+
//# sourceMappingURL=index.cjs.map
|
|
44
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/create-fetch-executor.ts"],"names":["createExecutor","serializeParams"],"mappings":";;;;;AA8BO,SAAS,mBAAA,CACd,SACA,OAAA,EAIU;AACV,EAAA,OAAOA,mBAAA,CAAe,OAAO,EAAE,MAAA,EAAQ,KAAK,MAAA,EAAQ,IAAA,EAAM,OAAA,EAAS,MAAA,EAAO,KAAM;AAC9E,IAAA,MAAM,OAAA,GAAU,IAAI,GAAA,CAAI,GAAA,EAAK,OAAO,CAAA;AACpC,IAAA,IAAI,MAAA,EAAQ;AACV,MAAAC,oBAAA,CAAgB,MAAM,CAAA,CAAE,OAAA,CAAQ,CAAC,CAAA,EAAG,CAAA,KAAM,OAAA,CAAQ,YAAA,CAAa,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAAA,IAC1E;AAEA,IAAA,MAAM,cAAA,GAAkB,MAAM,OAAA,EAAS,cAAA,QAAuB,EAAC;AAE/D,IAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,OAAA,CAAQ,UAAS,EAAG;AAAA,MAC1C,MAAA;AAAA,MACA,OAAA,EAAS;AAAA,QACP,GAAI,IAAA,IAAQ,IAAA,GAAO,EAAE,cAAA,EAAgB,kBAAA,KAAuB,EAAC;AAAA,QAC7D,GAAG,cAAA;AAAA,QACH,GAAG;AAAA,OACL;AAAA,MACA,MAAM,IAAA,IAAQ,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA,GAAI,MAAA;AAAA,MAC5C;AAAA,KACD,CAAA;AAED,IAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACX,MAAA,MAAM,IAAI,SAAA,CAAU,GAAA,CAAI,MAAA,EAAQ,IAAI,UAAU,CAAA;AAAA,IAChD;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,GAAA,IAAO,GAAA,CAAI,QAAQ,GAAA,CAAI,gBAAgB,MAAM,GAAA,EAAK;AACnE,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,IAAI,IAAA,EAAK;AAAA,EAClB,CAAA,EAAG,SAAS,WAAW,CAAA;AACzB;AAiBO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnC,WAAA,CAEkB,QAEA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,KAAA,EAAQ,MAAM,CAAA,EAAA,EAAK,UAAU,CAAA,CAAE,CAAA;AAJrB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAEA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AAAA,EACd;AACF","file":"index.cjs","sourcesContent":["import type { Executor, ExecutorMiddleware } from '@routar/core';\nimport { createExecutor, serializeParams } from '@routar/core';\n\n/**\n * Creates an {@link Executor} backed by the browser / Node.js `fetch` API.\n *\n * Suited for SSR environments where you need per-request dynamic headers\n * (e.g. forwarding auth cookies) without sharing state across requests.\n *\n * - Query params are serialized and appended to the URL.\n * - A `Content-Type: application/json` header is added automatically when\n * a request body is present.\n * - Responses with status 204 or `Content-Length: 0` resolve to `null`.\n * - Non-2xx responses throw an {@link HttpError}.\n *\n * @param baseURL - Absolute base URL prepended to every endpoint path.\n * @param options.defaultHeaders - Async factory called on every request to\n * produce headers (e.g. reading cookies in a Next.js server component).\n * @param options.middlewares - Middleware chain applied before the fetch call.\n *\n * @example\n * ```ts\n * const executor = createFetchExecutor('https://api.example.com', {\n * defaultHeaders: async () => {\n * const token = await getServerToken();\n * return token ? { Authorization: `Bearer ${token}` } : {};\n * },\n * });\n * ```\n */\nexport function createFetchExecutor(\n baseURL: string,\n options?: {\n defaultHeaders?: () => Record<string, string> | Promise<Record<string, string>>;\n middlewares?: ExecutorMiddleware[];\n },\n): Executor {\n return createExecutor(async ({ method, url, params, body, headers, signal }) => {\n const fullURL = new URL(url, baseURL);\n if (params) {\n serializeParams(params).forEach((v, k) => fullURL.searchParams.set(k, v));\n }\n\n const defaultHeaders = (await options?.defaultHeaders?.()) ?? {};\n\n const res = await fetch(fullURL.toString(), {\n method,\n headers: {\n ...(body != null ? { 'Content-Type': 'application/json' } : {}),\n ...defaultHeaders,\n ...headers,\n },\n body: body != null ? JSON.stringify(body) : undefined,\n signal,\n });\n\n if (!res.ok) {\n throw new HttpError(res.status, res.statusText);\n }\n if (res.status === 204 || res.headers.get('content-length') === '0') {\n return null;\n }\n return res.json();\n }, options?.middlewares);\n}\n\n/**\n * Thrown by {@link createFetchExecutor} when the server returns a non-2xx\n * status code.\n *\n * @example\n * ```ts\n * try {\n * await api.getDetail({ path: { id: 999 } });\n * } catch (err) {\n * if (err instanceof HttpError && err.status === 404) {\n * // handle not-found\n * }\n * }\n * ```\n */\nexport class HttpError extends Error {\n constructor(\n /** HTTP status code (e.g. 404, 500). */\n public readonly status: number,\n /** HTTP status text (e.g. \"Not Found\"). */\n public readonly statusText: string,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n this.name = 'HttpError';\n }\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { ExecutorMiddleware, Executor } from '@routar/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Creates an {@link Executor} backed by the browser / Node.js `fetch` API.
|
|
5
|
+
*
|
|
6
|
+
* Suited for SSR environments where you need per-request dynamic headers
|
|
7
|
+
* (e.g. forwarding auth cookies) without sharing state across requests.
|
|
8
|
+
*
|
|
9
|
+
* - Query params are serialized and appended to the URL.
|
|
10
|
+
* - A `Content-Type: application/json` header is added automatically when
|
|
11
|
+
* a request body is present.
|
|
12
|
+
* - Responses with status 204 or `Content-Length: 0` resolve to `null`.
|
|
13
|
+
* - Non-2xx responses throw an {@link HttpError}.
|
|
14
|
+
*
|
|
15
|
+
* @param baseURL - Absolute base URL prepended to every endpoint path.
|
|
16
|
+
* @param options.defaultHeaders - Async factory called on every request to
|
|
17
|
+
* produce headers (e.g. reading cookies in a Next.js server component).
|
|
18
|
+
* @param options.middlewares - Middleware chain applied before the fetch call.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* const executor = createFetchExecutor('https://api.example.com', {
|
|
23
|
+
* defaultHeaders: async () => {
|
|
24
|
+
* const token = await getServerToken();
|
|
25
|
+
* return token ? { Authorization: `Bearer ${token}` } : {};
|
|
26
|
+
* },
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare function createFetchExecutor(baseURL: string, options?: {
|
|
31
|
+
defaultHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
|
|
32
|
+
middlewares?: ExecutorMiddleware[];
|
|
33
|
+
}): Executor;
|
|
34
|
+
/**
|
|
35
|
+
* Thrown by {@link createFetchExecutor} when the server returns a non-2xx
|
|
36
|
+
* status code.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* try {
|
|
41
|
+
* await api.getDetail({ path: { id: 999 } });
|
|
42
|
+
* } catch (err) {
|
|
43
|
+
* if (err instanceof HttpError && err.status === 404) {
|
|
44
|
+
* // handle not-found
|
|
45
|
+
* }
|
|
46
|
+
* }
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
declare class HttpError extends Error {
|
|
50
|
+
/** HTTP status code (e.g. 404, 500). */
|
|
51
|
+
readonly status: number;
|
|
52
|
+
/** HTTP status text (e.g. "Not Found"). */
|
|
53
|
+
readonly statusText: string;
|
|
54
|
+
constructor(
|
|
55
|
+
/** HTTP status code (e.g. 404, 500). */
|
|
56
|
+
status: number,
|
|
57
|
+
/** HTTP status text (e.g. "Not Found"). */
|
|
58
|
+
statusText: string);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { HttpError, createFetchExecutor };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { ExecutorMiddleware, Executor } from '@routar/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Creates an {@link Executor} backed by the browser / Node.js `fetch` API.
|
|
5
|
+
*
|
|
6
|
+
* Suited for SSR environments where you need per-request dynamic headers
|
|
7
|
+
* (e.g. forwarding auth cookies) without sharing state across requests.
|
|
8
|
+
*
|
|
9
|
+
* - Query params are serialized and appended to the URL.
|
|
10
|
+
* - A `Content-Type: application/json` header is added automatically when
|
|
11
|
+
* a request body is present.
|
|
12
|
+
* - Responses with status 204 or `Content-Length: 0` resolve to `null`.
|
|
13
|
+
* - Non-2xx responses throw an {@link HttpError}.
|
|
14
|
+
*
|
|
15
|
+
* @param baseURL - Absolute base URL prepended to every endpoint path.
|
|
16
|
+
* @param options.defaultHeaders - Async factory called on every request to
|
|
17
|
+
* produce headers (e.g. reading cookies in a Next.js server component).
|
|
18
|
+
* @param options.middlewares - Middleware chain applied before the fetch call.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* const executor = createFetchExecutor('https://api.example.com', {
|
|
23
|
+
* defaultHeaders: async () => {
|
|
24
|
+
* const token = await getServerToken();
|
|
25
|
+
* return token ? { Authorization: `Bearer ${token}` } : {};
|
|
26
|
+
* },
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare function createFetchExecutor(baseURL: string, options?: {
|
|
31
|
+
defaultHeaders?: () => Record<string, string> | Promise<Record<string, string>>;
|
|
32
|
+
middlewares?: ExecutorMiddleware[];
|
|
33
|
+
}): Executor;
|
|
34
|
+
/**
|
|
35
|
+
* Thrown by {@link createFetchExecutor} when the server returns a non-2xx
|
|
36
|
+
* status code.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* try {
|
|
41
|
+
* await api.getDetail({ path: { id: 999 } });
|
|
42
|
+
* } catch (err) {
|
|
43
|
+
* if (err instanceof HttpError && err.status === 404) {
|
|
44
|
+
* // handle not-found
|
|
45
|
+
* }
|
|
46
|
+
* }
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
declare class HttpError extends Error {
|
|
50
|
+
/** HTTP status code (e.g. 404, 500). */
|
|
51
|
+
readonly status: number;
|
|
52
|
+
/** HTTP status text (e.g. "Not Found"). */
|
|
53
|
+
readonly statusText: string;
|
|
54
|
+
constructor(
|
|
55
|
+
/** HTTP status code (e.g. 404, 500). */
|
|
56
|
+
status: number,
|
|
57
|
+
/** HTTP status text (e.g. "Not Found"). */
|
|
58
|
+
statusText: string);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { HttpError, createFetchExecutor };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createExecutor, serializeParams } from '@routar/core';
|
|
2
|
+
|
|
3
|
+
// src/create-fetch-executor.ts
|
|
4
|
+
function createFetchExecutor(baseURL, options) {
|
|
5
|
+
return createExecutor(async ({ method, url, params, body, headers, signal }) => {
|
|
6
|
+
const fullURL = new URL(url, baseURL);
|
|
7
|
+
if (params) {
|
|
8
|
+
serializeParams(params).forEach((v, k) => fullURL.searchParams.set(k, v));
|
|
9
|
+
}
|
|
10
|
+
const defaultHeaders = await options?.defaultHeaders?.() ?? {};
|
|
11
|
+
const res = await fetch(fullURL.toString(), {
|
|
12
|
+
method,
|
|
13
|
+
headers: {
|
|
14
|
+
...body != null ? { "Content-Type": "application/json" } : {},
|
|
15
|
+
...defaultHeaders,
|
|
16
|
+
...headers
|
|
17
|
+
},
|
|
18
|
+
body: body != null ? JSON.stringify(body) : void 0,
|
|
19
|
+
signal
|
|
20
|
+
});
|
|
21
|
+
if (!res.ok) {
|
|
22
|
+
throw new HttpError(res.status, res.statusText);
|
|
23
|
+
}
|
|
24
|
+
if (res.status === 204 || res.headers.get("content-length") === "0") {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
return res.json();
|
|
28
|
+
}, options?.middlewares);
|
|
29
|
+
}
|
|
30
|
+
var HttpError = class extends Error {
|
|
31
|
+
constructor(status, statusText) {
|
|
32
|
+
super(`HTTP ${status}: ${statusText}`);
|
|
33
|
+
this.status = status;
|
|
34
|
+
this.statusText = statusText;
|
|
35
|
+
this.name = "HttpError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export { HttpError, createFetchExecutor };
|
|
40
|
+
//# sourceMappingURL=index.js.map
|
|
41
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/create-fetch-executor.ts"],"names":[],"mappings":";;;AA8BO,SAAS,mBAAA,CACd,SACA,OAAA,EAIU;AACV,EAAA,OAAO,cAAA,CAAe,OAAO,EAAE,MAAA,EAAQ,KAAK,MAAA,EAAQ,IAAA,EAAM,OAAA,EAAS,MAAA,EAAO,KAAM;AAC9E,IAAA,MAAM,OAAA,GAAU,IAAI,GAAA,CAAI,GAAA,EAAK,OAAO,CAAA;AACpC,IAAA,IAAI,MAAA,EAAQ;AACV,MAAA,eAAA,CAAgB,MAAM,CAAA,CAAE,OAAA,CAAQ,CAAC,CAAA,EAAG,CAAA,KAAM,OAAA,CAAQ,YAAA,CAAa,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAAA,IAC1E;AAEA,IAAA,MAAM,cAAA,GAAkB,MAAM,OAAA,EAAS,cAAA,QAAuB,EAAC;AAE/D,IAAA,MAAM,GAAA,GAAM,MAAM,KAAA,CAAM,OAAA,CAAQ,UAAS,EAAG;AAAA,MAC1C,MAAA;AAAA,MACA,OAAA,EAAS;AAAA,QACP,GAAI,IAAA,IAAQ,IAAA,GAAO,EAAE,cAAA,EAAgB,kBAAA,KAAuB,EAAC;AAAA,QAC7D,GAAG,cAAA;AAAA,QACH,GAAG;AAAA,OACL;AAAA,MACA,MAAM,IAAA,IAAQ,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA,GAAI,MAAA;AAAA,MAC5C;AAAA,KACD,CAAA;AAED,IAAA,IAAI,CAAC,IAAI,EAAA,EAAI;AACX,MAAA,MAAM,IAAI,SAAA,CAAU,GAAA,CAAI,MAAA,EAAQ,IAAI,UAAU,CAAA;AAAA,IAChD;AACA,IAAA,IAAI,GAAA,CAAI,WAAW,GAAA,IAAO,GAAA,CAAI,QAAQ,GAAA,CAAI,gBAAgB,MAAM,GAAA,EAAK;AACnE,MAAA,OAAO,IAAA;AAAA,IACT;AACA,IAAA,OAAO,IAAI,IAAA,EAAK;AAAA,EAClB,CAAA,EAAG,SAAS,WAAW,CAAA;AACzB;AAiBO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EACnC,WAAA,CAEkB,QAEA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,CAAA,KAAA,EAAQ,MAAM,CAAA,EAAA,EAAK,UAAU,CAAA,CAAE,CAAA;AAJrB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAEA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AAAA,EACd;AACF","file":"index.js","sourcesContent":["import type { Executor, ExecutorMiddleware } from '@routar/core';\nimport { createExecutor, serializeParams } from '@routar/core';\n\n/**\n * Creates an {@link Executor} backed by the browser / Node.js `fetch` API.\n *\n * Suited for SSR environments where you need per-request dynamic headers\n * (e.g. forwarding auth cookies) without sharing state across requests.\n *\n * - Query params are serialized and appended to the URL.\n * - A `Content-Type: application/json` header is added automatically when\n * a request body is present.\n * - Responses with status 204 or `Content-Length: 0` resolve to `null`.\n * - Non-2xx responses throw an {@link HttpError}.\n *\n * @param baseURL - Absolute base URL prepended to every endpoint path.\n * @param options.defaultHeaders - Async factory called on every request to\n * produce headers (e.g. reading cookies in a Next.js server component).\n * @param options.middlewares - Middleware chain applied before the fetch call.\n *\n * @example\n * ```ts\n * const executor = createFetchExecutor('https://api.example.com', {\n * defaultHeaders: async () => {\n * const token = await getServerToken();\n * return token ? { Authorization: `Bearer ${token}` } : {};\n * },\n * });\n * ```\n */\nexport function createFetchExecutor(\n baseURL: string,\n options?: {\n defaultHeaders?: () => Record<string, string> | Promise<Record<string, string>>;\n middlewares?: ExecutorMiddleware[];\n },\n): Executor {\n return createExecutor(async ({ method, url, params, body, headers, signal }) => {\n const fullURL = new URL(url, baseURL);\n if (params) {\n serializeParams(params).forEach((v, k) => fullURL.searchParams.set(k, v));\n }\n\n const defaultHeaders = (await options?.defaultHeaders?.()) ?? {};\n\n const res = await fetch(fullURL.toString(), {\n method,\n headers: {\n ...(body != null ? { 'Content-Type': 'application/json' } : {}),\n ...defaultHeaders,\n ...headers,\n },\n body: body != null ? JSON.stringify(body) : undefined,\n signal,\n });\n\n if (!res.ok) {\n throw new HttpError(res.status, res.statusText);\n }\n if (res.status === 204 || res.headers.get('content-length') === '0') {\n return null;\n }\n return res.json();\n }, options?.middlewares);\n}\n\n/**\n * Thrown by {@link createFetchExecutor} when the server returns a non-2xx\n * status code.\n *\n * @example\n * ```ts\n * try {\n * await api.getDetail({ path: { id: 999 } });\n * } catch (err) {\n * if (err instanceof HttpError && err.status === 404) {\n * // handle not-found\n * }\n * }\n * ```\n */\nexport class HttpError extends Error {\n constructor(\n /** HTTP status code (e.g. 404, 500). */\n public readonly status: number,\n /** HTTP status text (e.g. \"Not Found\"). */\n public readonly statusText: string,\n ) {\n super(`HTTP ${status}: ${statusText}`);\n this.name = 'HttpError';\n }\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@routar/fetch",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Fetch-based executor for routar — transport adapter using the native fetch API",
|
|
5
|
+
"keywords": ["api", "http", "typescript", "fetch", "routar", "executor"],
|
|
6
|
+
"author": "Kyungbae Min",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/minr2kb/routar.git",
|
|
11
|
+
"directory": "packages/fetch"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/minr2kb/routar#readme",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js",
|
|
19
|
+
"require": "./dist/index.cjs"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/index.cjs",
|
|
23
|
+
"module": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsup",
|
|
28
|
+
"dev": "tsup --watch"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@routar/core": "^0.1.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@routar/core": "workspace:*",
|
|
35
|
+
"tsup": "^8.5.1"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": { "access": "public" }
|
|
38
|
+
}
|