flaks-request 1.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/index.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require("./src");
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "flaks-request",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight lib for requests",
5
+ "keywords": [
6
+ "flaks",
7
+ "request"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "Flaks",
11
+ "type": "commonjs",
12
+ "main": "index.js",
13
+ "scripts": {
14
+ "typecheck": "tsc --project jsconfig.json"
15
+ },
16
+ "devDependencies": {
17
+ "typescript": "^6.0.3",
18
+ "@types/node": "^24.12.0"
19
+ },
20
+ "files": [
21
+ "src/**/*",
22
+ "index.js"
23
+ ]
24
+ }
package/src/index.js ADDED
@@ -0,0 +1,137 @@
1
+ const { WriteStream } = require("node:fs");
2
+ const { pipeline } = require("node:stream/promises");
3
+
4
+ /**
5
+ *
6
+ * @param {object} obj
7
+ * @param {string} [prefix]
8
+ * @returns
9
+ */
10
+ function buildSearchParams(obj, prefix = "") {
11
+ const params = new URLSearchParams();
12
+
13
+ for (const [key, value] of Object.entries(obj)) {
14
+ const paramKey = prefix ? `${prefix}[${key}]` : key;
15
+
16
+ if (value && typeof value === "object" && !Array.isArray(value)) {
17
+ const nested = buildSearchParams(value, paramKey);
18
+
19
+ for (const [k, v] of nested.entries()) {
20
+ params.append(k, v);
21
+ }
22
+ } else if (value != null) {
23
+ params.append(paramKey, String(value));
24
+ }
25
+ }
26
+
27
+ return params;
28
+ }
29
+
30
+ function getTimeout(timeoutMs = 30e3) {
31
+ const controller = new AbortController();
32
+ /** @type {RequestInit['signal']} */ // @ts-ignore
33
+ const signal = controller.signal;
34
+
35
+ const timeout = setTimeout(() => {
36
+ controller.abort();
37
+ }, timeoutMs);
38
+
39
+ return { timeout, controller, signal };
40
+ }
41
+
42
+ /**
43
+ *
44
+ * @param {import("./types").RequestOptions} requestOptions
45
+ */
46
+ function resolveUrl(requestOptions) {
47
+ let url = requestOptions.path;
48
+
49
+ if (requestOptions.baseUrl) {
50
+ if (url[0] === "/") url = url.slice(1);
51
+
52
+ url = `${requestOptions.baseUrl}/${url}`;
53
+ }
54
+
55
+ if (requestOptions.search) {
56
+ const search = buildSearchParams(requestOptions.search);
57
+ url += `?${search.toString()}`;
58
+ }
59
+
60
+ return url;
61
+ }
62
+
63
+ /**
64
+ *
65
+ * @param {import("./types").RequestOptions} requestOptions
66
+ */
67
+ async function request(requestOptions) {
68
+ const { method = "GET", timeoutMs = 40e3 } = requestOptions;
69
+
70
+ const url = resolveUrl(requestOptions);
71
+ const { timeout, signal } = getTimeout(timeoutMs);
72
+
73
+ /** @type {RequestInit} */
74
+ const options = {
75
+ method,
76
+ headers: requestOptions.headers,
77
+ signal,
78
+ };
79
+
80
+ if (requestOptions.json) {
81
+ options.body = JSON.stringify(requestOptions.json);
82
+ }
83
+
84
+ try {
85
+ const res = await fetch(url, options);
86
+
87
+ /** @type {string | unknown} */
88
+ let responseBody;
89
+
90
+ try {
91
+ responseBody = await (requestOptions.rawBody ? res.text() : res.json());
92
+ } catch {
93
+ responseBody = undefined;
94
+ }
95
+
96
+ return {
97
+ body: responseBody,
98
+ status: res.status,
99
+ request: {
100
+ url,
101
+ options,
102
+ },
103
+ };
104
+ } catch (err) {
105
+ if (err.name === "AbortError") {
106
+ throw new Error("REQUEST_TIMEDOUT");
107
+ }
108
+
109
+ throw err;
110
+ } finally {
111
+ clearTimeout(timeout);
112
+ }
113
+ }
114
+
115
+ /**
116
+ *
117
+ * @param {import("./types").RequestOptions} requestOptions
118
+ * @param {WriteStream} stream
119
+ */
120
+ async function requestFile(requestOptions, stream) {
121
+ const { timeout, signal } = getTimeout(requestOptions.timeoutMs);
122
+ const url = resolveUrl(requestOptions);
123
+
124
+ try {
125
+ const response = await fetch(url, { signal });
126
+
127
+ if (!response.ok || !response.body) {
128
+ throw new Error(`HTTP ${response.status} ${response.statusText}`);
129
+ }
130
+
131
+ await pipeline(response.body, stream);
132
+ } finally {
133
+ clearTimeout(timeout);
134
+ }
135
+ }
136
+
137
+ module.exports = { request, requestFile, buildSearchParams };
package/src/types.ts ADDED
@@ -0,0 +1,12 @@
1
+ export interface RequestOptions {
2
+ headers?: Record<string, string>;
3
+ search?: Record<string, unknown>;
4
+ json?: unknown;
5
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
6
+ path: string;
7
+ baseUrl?: string;
8
+ timeoutMs?: number;
9
+
10
+ /** JSON by default */
11
+ rawBody?: boolean;
12
+ }