flaks-request 1.0.0 → 1.0.1

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.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/src/index.js +189 -65
  3. package/src/types.ts +23 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flaks-request",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Lightweight lib for requests",
5
5
  "keywords": [
6
6
  "flaks",
package/src/index.js CHANGED
@@ -1,10 +1,16 @@
1
+ /** @import { RequestHandler, RequestOptions, RequestResponse, SearchParamsObject } from './types' */
2
+
1
3
  const { WriteStream } = require("node:fs");
2
4
  const { pipeline } = require("node:stream/promises");
5
+ const { IncomingMessage } = require("node:http");
6
+
7
+ const https = require("https");
8
+ const http = require("http");
3
9
 
4
10
  /**
5
11
  *
6
- * @param {object} obj
7
- * @param {string} [prefix]
12
+ * @param {SearchParamsObject} obj
13
+ * @param {string} prefix
8
14
  * @returns
9
15
  */
10
16
  function buildSearchParams(obj, prefix = "") {
@@ -27,21 +33,9 @@ function buildSearchParams(obj, prefix = "") {
27
33
  return params;
28
34
  }
29
35
 
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
36
  /**
43
37
  *
44
- * @param {import("./types").RequestOptions} requestOptions
38
+ * @param {RequestOptions} requestOptions
45
39
  */
46
40
  function resolveUrl(requestOptions) {
47
41
  let url = requestOptions.path;
@@ -62,76 +56,206 @@ function resolveUrl(requestOptions) {
62
56
 
63
57
  /**
64
58
  *
65
- * @param {import("./types").RequestOptions} requestOptions
59
+ * @param {RequestOptions} requestOptions
60
+ * @param {RequestHandler} responseHandler
66
61
  */
67
- async function request(requestOptions) {
68
- const { method = "GET", timeoutMs = 40e3 } = requestOptions;
62
+ function handleRequest(requestOptions, responseHandler) {
63
+ const { timeoutMs = 40e3 } = requestOptions;
64
+ const maxRedirects = requestOptions.maxRedirects ?? 2;
69
65
 
70
- const url = resolveUrl(requestOptions);
71
- const { timeout, signal } = getTimeout(timeoutMs);
66
+ requestOptions.headers ??= {};
67
+ const { headers } = requestOptions;
72
68
 
73
- /** @type {RequestInit} */
74
- const options = {
75
- method,
76
- headers: requestOptions.headers,
77
- signal,
78
- };
69
+ /** @type {string[]} */
70
+ const redirectUrls = [];
79
71
 
80
- if (requestOptions.json) {
81
- options.body = JSON.stringify(requestOptions.json);
72
+ /** @type {string | undefined} */
73
+ let bodyData;
74
+
75
+ if (requestOptions.json !== undefined) {
76
+ bodyData = JSON.stringify(requestOptions.json);
77
+ headers["Content-Length"] = Buffer.byteLength(bodyData).toString();
78
+ headers["Content-Type"] = "application/json";
82
79
  }
83
80
 
84
- try {
85
- const res = await fetch(url, options);
81
+ return doRequest(resolveUrl(requestOptions));
86
82
 
87
- /** @type {string | unknown} */
88
- let responseBody;
83
+ /**
84
+ *
85
+ * @param {string} url
86
+ * @param {number} redirectCounter
87
+ * @returns
88
+ */
89
+ function doRequest(url, redirectCounter = 0, nextOptions = requestOptions) {
90
+ const { promise, reject, resolve } = Promise.withResolvers();
89
91
 
90
- try {
91
- responseBody = await (requestOptions.rawBody ? res.text() : res.json());
92
- } catch {
93
- responseBody = undefined;
94
- }
92
+ /** @param {IncomingMessage} res */
93
+ const cb = (res) => {
94
+ const status = res.statusCode ?? 0;
95
+
96
+ if (redirectCounter) {
97
+ redirectUrls.push(url);
98
+ }
99
+
100
+ // Follow redirects
101
+ if ([301, 302, 303, 307, 308].includes(status) && res.headers.location) {
102
+ res.resume();
103
+
104
+ if (redirectCounter >= maxRedirects) {
105
+ reject(new Error("Too many redirects"));
106
+ return;
107
+ }
108
+
109
+ const nextUrl = new URL(res.headers.location, url);
110
+
111
+ nextOptions = {
112
+ ...nextOptions,
113
+ headers: { ...nextOptions.headers },
114
+ };
115
+
116
+ const clearOptions = () => {
117
+ nextOptions.method = "GET";
118
+ if (!nextOptions.headers) return;
119
+
120
+ delete nextOptions.headers["Content-Length"];
121
+ delete nextOptions.headers["Content-Type"];
122
+ };
123
+
124
+ /**
125
+ * Historically:
126
+ *
127
+ * GET → 301/302 → GET
128
+ * HEAD → 301/302 → HEAD
129
+ * POST → 301/302 → most clients change to GET
130
+ */
131
+ if (status === 303) {
132
+ clearOptions();
133
+ } else if ((status === 301 || status === 302) && requestOptions.method?.toUpperCase() === "POST") {
134
+ clearOptions();
135
+ }
136
+
137
+ doRequest(nextUrl.href, redirectCounter + 1, nextOptions)
138
+ .then(resolve)
139
+ .catch(reject);
140
+
141
+ return;
142
+ }
143
+
144
+ if (status < 200 || status >= 300) {
145
+ /** @type {Buffer[]} */
146
+ const chunks = [];
147
+
148
+ res.on("data", (chunk) => chunks.push(chunk));
149
+
150
+ res.on("end", () => {
151
+ const body = Buffer.concat(chunks).toString();
152
+ const msgs = [`Status:${status}`];
153
+
154
+ if (redirectUrls.length) msgs.push(`\nRedirects:\n${redirectUrls.join("\n")}`);
155
+ msgs.push(`\nReq:${JSON.stringify(requestOptions, null, 2)}`);
156
+ msgs.push(`\nBody:\n${body}`);
157
+
158
+ const msg = msgs.join(" ");
159
+ reject(new Error(msg));
160
+ });
161
+
162
+ res.on("error", reject);
163
+ return;
164
+ }
95
165
 
96
- return {
97
- body: responseBody,
98
- status: res.status,
99
- request: {
100
- url,
101
- options,
102
- },
166
+ return responseHandler(res, resolve, reject);
103
167
  };
104
- } catch (err) {
105
- if (err.name === "AbortError") {
106
- throw new Error("REQUEST_TIMEDOUT");
168
+
169
+ const parsed = new URL(url);
170
+ const isHttps = url.startsWith("https://");
171
+ parsed.port ??= (isHttps ? 443 : 80).toString();
172
+
173
+ /** @type {https.RequestOptions | http.RequestOptions} */
174
+ const options = {
175
+ ...requestOptions,
176
+
177
+ protocol: parsed.protocol,
178
+ hostname: parsed.hostname,
179
+ path: parsed.pathname + parsed.search,
180
+ port: parsed.port,
181
+ };
182
+
183
+ const req = isHttps ? https.request(options, cb) : http.request(options, cb);
184
+
185
+ req.setTimeout(timeoutMs, () => {
186
+ req.destroy(new Error("REQUEST_TIMEDOUT"));
187
+ });
188
+
189
+ req.on("error", reject);
190
+
191
+ if (bodyData) {
192
+ req.write(bodyData);
107
193
  }
108
194
 
109
- throw err;
110
- } finally {
111
- clearTimeout(timeout);
195
+ req.end();
196
+
197
+ return promise;
112
198
  }
113
199
  }
114
200
 
115
201
  /**
116
202
  *
117
- * @param {import("./types").RequestOptions} requestOptions
118
- * @param {WriteStream} stream
203
+ * @param {RequestOptions} requestOptions
204
+ *
205
+ * @returns {Promise<RequestResponse>}
119
206
  */
120
- async function requestFile(requestOptions, stream) {
121
- const { timeout, signal } = getTimeout(requestOptions.timeoutMs);
122
- const url = resolveUrl(requestOptions);
207
+ async function request(requestOptions) {
208
+ return handleRequest(requestOptions, (res, resolve, reject) => {
209
+ /** @type {Buffer[]} */
210
+ const chunks = [];
123
211
 
124
- try {
125
- const response = await fetch(url, { signal });
212
+ res.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
213
+ res.on("error", reject);
126
214
 
127
- if (!response.ok || !response.body) {
128
- throw new Error(`HTTP ${response.status} ${response.statusText}`);
129
- }
215
+ res.on("end", () => {
216
+ const text = Buffer.concat(chunks).toString();
130
217
 
131
- await pipeline(response.body, stream);
132
- } finally {
133
- clearTimeout(timeout);
134
- }
218
+ let body = text;
219
+ let isJson = false;
220
+
221
+ try {
222
+ body = JSON.parse(text);
223
+ isJson = true;
224
+ } catch {
225
+ // keep text body
226
+ }
227
+
228
+ resolve({
229
+ success: true,
230
+ isJson,
231
+ body,
232
+ status: res.statusCode,
233
+ requestOptions,
234
+ });
235
+ });
236
+ });
237
+ }
238
+ /**
239
+ *
240
+ * @param {RequestOptions} requestOptions
241
+ */
242
+ function requestHeaders(requestOptions) {
243
+ return handleRequest(requestOptions, (res, resolve) => {
244
+ res.destroy();
245
+
246
+ resolve({ status: res.statusCode, headers: res.headers });
247
+ });
248
+ }
249
+
250
+ /**
251
+ *
252
+ * @param {RequestOptions} requestOptions
253
+ * @param {WriteStream} stream
254
+ */
255
+ function requestFile(requestOptions, stream) {
256
+ return handleRequest(requestOptions, (res, resolve, reject) => {
257
+ pipeline(res, stream).then(resolve).catch(reject);
258
+ });
135
259
  }
136
260
 
137
- module.exports = { request, requestFile, buildSearchParams };
261
+ module.exports = { request, requestHeaders, requestFile, buildSearchParams };
package/src/types.ts CHANGED
@@ -1,12 +1,32 @@
1
+ import { IncomingMessage } from "node:http";
2
+
3
+ type SearchParamsValue = string | number | boolean | null | undefined | SearchParamsObject | unknown[];
4
+
5
+ export interface SearchParamsObject {
6
+ [key: string]: SearchParamsValue;
7
+ }
8
+
1
9
  export interface RequestOptions {
2
10
  headers?: Record<string, string>;
3
- search?: Record<string, unknown>;
11
+ search?: SearchParamsObject;
4
12
  json?: unknown;
5
13
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
6
14
  path: string;
7
15
  baseUrl?: string;
8
16
  timeoutMs?: number;
17
+ maxRedirects?: number;
18
+ }
19
+
20
+ export type RequestHandler = (
21
+ res: IncomingMessage,
22
+ resolve: (value: any) => void,
23
+ reject: (err: Error) => void,
24
+ ) => void;
9
25
 
10
- /** JSON by default */
11
- rawBody?: boolean;
26
+ export interface RequestResponse {
27
+ success: boolean;
28
+ isJson: boolean;
29
+ body: string | any;
30
+ status: string;
31
+ requestOptions: RequestOptions;
12
32
  }