@kosmojs/fetch 0.0.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/package.json +30 -0
- package/pkg/index.js +125 -0
- package/pkg/index.js.map +7 -0
- package/pkg/src/defaults.d.ts +13 -0
- package/pkg/src/index.d.ts +7 -0
- package/pkg/src/types.d.ts +15 -0
- package/pkg/test/fetch.test.d.ts +1 -0
- package/pkg/test/mocks.d.ts +1 -0
- package/pkg/test/setup.d.ts +1 -0
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"type": "module",
|
|
3
|
+
"name": "@kosmojs/fetch",
|
|
4
|
+
"version": "0.0.0",
|
|
5
|
+
"author": "Slee Woo",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"pkg/*"
|
|
12
|
+
],
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./pkg/src/index.d.ts",
|
|
16
|
+
"default": "./pkg/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"qs": "^6.14.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/qs": "^6.14.0",
|
|
24
|
+
"@kosmojs/config": "^0.0.0"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "esbuilder src/index.ts",
|
|
28
|
+
"test": "vitest --root ../../.. --project core/fetch"
|
|
29
|
+
}
|
|
30
|
+
}
|
package/pkg/index.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import qs from "qs";
|
|
3
|
+
|
|
4
|
+
// src/defaults.ts
|
|
5
|
+
var defaults_default = {
|
|
6
|
+
responseMode: "json",
|
|
7
|
+
get headers() {
|
|
8
|
+
return {
|
|
9
|
+
Accept: "application/json",
|
|
10
|
+
"Content-Type": "application/json"
|
|
11
|
+
};
|
|
12
|
+
},
|
|
13
|
+
stringify: (o) => new URLSearchParams(o).toString(),
|
|
14
|
+
errorHandler: console.error
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/index.ts
|
|
18
|
+
var bodylessMethods = ["GET", "DELETE"];
|
|
19
|
+
var index_default = (base, opts) => {
|
|
20
|
+
const {
|
|
21
|
+
headers: _headers,
|
|
22
|
+
responseMode,
|
|
23
|
+
stringify: stringify2,
|
|
24
|
+
errorHandler,
|
|
25
|
+
...fetchOpts
|
|
26
|
+
// Remaining options passed directly to fetch
|
|
27
|
+
} = {
|
|
28
|
+
...defaults_default,
|
|
29
|
+
...opts
|
|
30
|
+
};
|
|
31
|
+
const headers = new Headers({
|
|
32
|
+
..._headers instanceof Headers ? Object.fromEntries(_headers.entries()) : _headers
|
|
33
|
+
// Use as-is if already a plain object
|
|
34
|
+
});
|
|
35
|
+
function wrapper(method) {
|
|
36
|
+
function _wrapper(path, data) {
|
|
37
|
+
const url = [
|
|
38
|
+
String(base),
|
|
39
|
+
...Array.isArray(path) ? path : ["string", "number"].includes(typeof path) ? [path] : []
|
|
40
|
+
// No path provided
|
|
41
|
+
].join("/");
|
|
42
|
+
const optedContentType = opts?.headers instanceof Headers ? opts.headers.get("Content-Type") : opts?.headers?.["Content-Type"];
|
|
43
|
+
if (responseMode !== defaults_default.responseMode && !optedContentType) {
|
|
44
|
+
const contentType = {
|
|
45
|
+
text: "text/plain",
|
|
46
|
+
blob: data instanceof Blob ? data.type : void 0,
|
|
47
|
+
formData: null,
|
|
48
|
+
// Let browser set multipart boundary
|
|
49
|
+
arrayBuffer: null,
|
|
50
|
+
// No content-type needed
|
|
51
|
+
raw: void 0
|
|
52
|
+
// Don't modify
|
|
53
|
+
}[responseMode];
|
|
54
|
+
if (contentType === null) {
|
|
55
|
+
headers.delete("Content-Type");
|
|
56
|
+
} else if (contentType) {
|
|
57
|
+
headers.set("Content-Type", contentType);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
let searchParams = "";
|
|
61
|
+
let body = JSON.stringify({});
|
|
62
|
+
if (data instanceof Blob || data instanceof FormData || Object.prototype.toString.call(data) === "[object ArrayBuffer]") {
|
|
63
|
+
body = data;
|
|
64
|
+
} else if (typeof data === "string") {
|
|
65
|
+
if (bodylessMethods.includes(method)) {
|
|
66
|
+
searchParams = data;
|
|
67
|
+
} else {
|
|
68
|
+
body = data;
|
|
69
|
+
}
|
|
70
|
+
} else if (typeof data === "object") {
|
|
71
|
+
if (bodylessMethods.includes(method)) {
|
|
72
|
+
searchParams = stringify2(data);
|
|
73
|
+
} else {
|
|
74
|
+
body = JSON.stringify({ ...data });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const config = {
|
|
78
|
+
...fetchOpts,
|
|
79
|
+
method,
|
|
80
|
+
headers,
|
|
81
|
+
// Only include body for non-bodyless methods
|
|
82
|
+
...bodylessMethods.includes(method) ? {} : { body }
|
|
83
|
+
};
|
|
84
|
+
return fetch([url, searchParams].join("?"), config).then((response) => {
|
|
85
|
+
return Promise.all([
|
|
86
|
+
response,
|
|
87
|
+
responseMode === "raw" ? response : response[responseMode]().catch(() => null)
|
|
88
|
+
// Parse response body
|
|
89
|
+
]);
|
|
90
|
+
}).then(([response, data2]) => {
|
|
91
|
+
if (response.ok) {
|
|
92
|
+
return data2;
|
|
93
|
+
}
|
|
94
|
+
const error = new Error(
|
|
95
|
+
data2?.error || response.statusText
|
|
96
|
+
);
|
|
97
|
+
error.response = response;
|
|
98
|
+
error.body = data2;
|
|
99
|
+
errorHandler?.(error);
|
|
100
|
+
throw error;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return _wrapper;
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
GET: wrapper("GET"),
|
|
107
|
+
POST: wrapper("POST"),
|
|
108
|
+
PUT: wrapper("PUT"),
|
|
109
|
+
PATCH: wrapper("PATCH"),
|
|
110
|
+
DELETE: wrapper("DELETE")
|
|
111
|
+
};
|
|
112
|
+
};
|
|
113
|
+
var stringify = (data) => {
|
|
114
|
+
return qs.stringify(data, {
|
|
115
|
+
arrayFormat: "brackets",
|
|
116
|
+
indices: false,
|
|
117
|
+
encodeValuesOnly: true
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
export {
|
|
121
|
+
index_default as default,
|
|
122
|
+
defaults_default as defaults,
|
|
123
|
+
stringify
|
|
124
|
+
};
|
|
125
|
+
//# sourceMappingURL=index.js.map
|
package/pkg/index.js.map
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts", "../src/defaults.ts"],
|
|
4
|
+
"sourcesContent": ["import qs from \"qs\";\n\nimport defaults from \"./defaults\";\nimport type {\n FetchMapper,\n FetchMethod,\n HTTPError,\n HTTPMethod,\n Options,\n} from \"./types\";\n\nexport { defaults };\n\nexport * from \"./types\";\n\n// Supported data types for request body\ntype Data = Record<string, unknown> | FormData | ArrayBuffer | Blob | string;\n\n// Path can be a string, number, or array of these\ntype PathEntry = string | number;\n\n// HTTP methods that typically don't include a request body\nconst bodylessMethods = [\"GET\", \"DELETE\"];\n\n// Main factory function that creates a configured fetch client instance\nexport default (base: string | URL, opts?: Options): FetchMapper => {\n // Merge provided options with defaults, extracting specific properties\n const {\n headers: _headers,\n responseMode,\n stringify,\n errorHandler,\n ...fetchOpts // Remaining options passed directly to fetch\n } = {\n ...defaults,\n ...opts,\n };\n\n // Normalize headers to Headers instance for consistent API\n const headers = new Headers({\n ...(_headers instanceof Headers\n ? Object.fromEntries(_headers.entries()) // Convert Headers to plain object\n : _headers), // Use as-is if already a plain object\n });\n\n // Factory function that creates HTTP method implementations\n function wrapper(method: HTTPMethod): FetchMethod {\n // Function overloads for TypeScript type checking\n // No path, no data\n function _wrapper<T>(): Promise<T>;\n // Path without data\n function _wrapper<T>(path: PathEntry | Array<PathEntry>): Promise<T>;\n // Path with data\n function _wrapper<T>(\n path: PathEntry | Array<PathEntry>,\n data: Data,\n ): Promise<T>;\n\n // Main implementation function\n function _wrapper<T>(\n path?: PathEntry | Array<PathEntry>,\n data?: Data,\n ): Promise<T> {\n // Construct URL from base and path segments\n const url = [\n String(base),\n ...(Array.isArray(path)\n ? path // Use array as-is\n : [\"string\", \"number\"].includes(typeof path)\n ? [path] // Wrap single value in array\n : []), // No path provided\n ].join(\"/\");\n\n // Check if content-type was explicitly set in options\n const optedContentType =\n opts?.headers instanceof Headers\n ? opts.headers.get(\"Content-Type\")\n : opts?.headers?.[\"Content-Type\"];\n\n // Auto-set Content-Type header based on response mode if not explicitly set\n if (responseMode !== defaults.responseMode && !optedContentType) {\n const contentType = {\n text: \"text/plain\",\n blob: data instanceof Blob ? data.type : undefined,\n formData: null, // Let browser set multipart boundary\n arrayBuffer: null, // No content-type needed\n raw: undefined, // Don't modify\n }[responseMode];\n\n if (contentType === null) {\n headers.delete(\"Content-Type\");\n } else if (contentType) {\n headers.set(\"Content-Type\", contentType);\n }\n }\n\n let searchParams = \"\";\n\n // Default empty body\n let body: string | FormData | ArrayBuffer | Blob = JSON.stringify({});\n\n // Handle different data types for request body\n if (\n data instanceof Blob ||\n data instanceof FormData ||\n Object.prototype.toString.call(data) === \"[object ArrayBuffer]\"\n ) {\n // Use binary data as-is\n body = data as typeof body;\n } else if (typeof data === \"string\") {\n if (bodylessMethods.includes(method)) {\n // For GET/DELETE, add string data as query params\n searchParams = data;\n } else {\n // For other methods, use as body\n body = data;\n }\n } else if (typeof data === \"object\") {\n if (bodylessMethods.includes(method)) {\n // For GET/DELETE, serialize object to query string\n searchParams = stringify(data as Record<string, string>);\n } else {\n // For other methods, serialize as JSON\n body = JSON.stringify({ ...data });\n }\n }\n\n // Prepare fetch configuration\n const config: Options & { method: HTTPMethod; body?: typeof body } = {\n ...fetchOpts,\n method,\n headers,\n // Only include body for non-bodyless methods\n ...(bodylessMethods.includes(method) ? {} : { body }),\n };\n\n // Execute fetch request and process response\n return fetch([url, searchParams].join(\"?\"), config)\n .then((response) => {\n // Return both response and parsed data based on responseMode\n return Promise.all([\n response,\n responseMode === \"raw\"\n ? response // Return full response object\n : response[responseMode]().catch(() => null), // Parse response body\n ]);\n })\n .then(([response, data]) => {\n if (response.ok) {\n return data; // Return parsed data for successful responses\n }\n // Create enhanced error object for HTTP errors\n const error = new Error(\n data?.error || response.statusText,\n ) as HTTPError;\n error.response = response;\n error.body = data;\n errorHandler?.(error); // Call custom error handler if provided\n throw error;\n });\n }\n\n return _wrapper;\n }\n\n // Return object with HTTP method functions\n return {\n GET: wrapper(\"GET\"),\n POST: wrapper(\"POST\"),\n PUT: wrapper(\"PUT\"),\n PATCH: wrapper(\"PATCH\"),\n DELETE: wrapper(\"DELETE\"),\n };\n};\n\nexport const stringify = (data: Record<string, unknown>) => {\n return qs.stringify(data, {\n arrayFormat: \"brackets\",\n indices: false,\n encodeValuesOnly: true,\n });\n};\n", "export default {\n responseMode: \"json\",\n get headers() {\n return {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n };\n },\n stringify: (o) => new URLSearchParams(o as never).toString(),\n errorHandler: console.error,\n} satisfies import(\"./types\").Defaults;\n"],
|
|
5
|
+
"mappings": ";AAAA,OAAO,QAAQ;;;ACAf,IAAO,mBAAQ;AAAA,EACb,cAAc;AAAA,EACd,IAAI,UAAU;AACZ,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,gBAAgB;AAAA,IAClB;AAAA,EACF;AAAA,EACA,WAAW,CAAC,MAAM,IAAI,gBAAgB,CAAU,EAAE,SAAS;AAAA,EAC3D,cAAc,QAAQ;AACxB;;;ADYA,IAAM,kBAAkB,CAAC,OAAO,QAAQ;AAGxC,IAAO,gBAAQ,CAAC,MAAoB,SAAgC;AAElE,QAAM;AAAA,IACJ,SAAS;AAAA,IACT;AAAA,IACA,WAAAA;AAAA,IACA;AAAA,IACA,GAAG;AAAA;AAAA,E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: "json";
|
|
3
|
+
readonly headers: {
|
|
4
|
+
Accept: string;
|
|
5
|
+
"Content-Type": string;
|
|
6
|
+
};
|
|
7
|
+
stringify: (o: Record<string, unknown>) => string;
|
|
8
|
+
errorHandler: {
|
|
9
|
+
(...data: any[]): void;
|
|
10
|
+
(message?: any, ...optionalParams: any[]): void;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
export default _default;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import defaults from "./defaults";
|
|
2
|
+
import type { FetchMapper, Options } from "./types";
|
|
3
|
+
export { defaults };
|
|
4
|
+
export * from "./types";
|
|
5
|
+
declare const _default: (base: string | URL, opts?: Options) => FetchMapper;
|
|
6
|
+
export default _default;
|
|
7
|
+
export declare const stringify: (data: Record<string, unknown>) => string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface Defaults {
|
|
2
|
+
responseMode: ResponseMode;
|
|
3
|
+
headers: Record<string, string> | Headers;
|
|
4
|
+
stringify: (d: Record<string, unknown>) => string;
|
|
5
|
+
errorHandler: (e: unknown) => void;
|
|
6
|
+
}
|
|
7
|
+
export type HTTPMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
8
|
+
export type ResponseMode = "json" | "text" | "blob" | "formData" | "arrayBuffer" | "raw";
|
|
9
|
+
export type Options = Partial<Defaults> & Pick<RequestInit, "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window">;
|
|
10
|
+
export type FetchMethod = <T = unknown>(...a: Array<unknown>) => Promise<T>;
|
|
11
|
+
export type FetchMapper = Record<HTTPMethod, FetchMethod>;
|
|
12
|
+
export interface HTTPError<T extends object = object> extends Error {
|
|
13
|
+
body: T;
|
|
14
|
+
response: Response;
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const server: import("msw/node").SetupServerApi;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|