flaks-request 1.0.0 → 1.0.2

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