flaks-request 1.0.1 → 1.0.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flaks-request",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Lightweight lib for requests",
5
5
  "keywords": [
6
6
  "flaks",
package/src/index.js CHANGED
@@ -1,4 +1,4 @@
1
- /** @import { RequestHandler, RequestOptions, RequestResponse, SearchParamsObject } from './types' */
1
+ /** @import { JsonValue, RequestHandler, RequestOptions, RequestResponse, SearchParamsObject } from './types' */
2
2
 
3
3
  const { WriteStream } = require("node:fs");
4
4
  const { pipeline } = require("node:stream/promises");
@@ -33,6 +33,18 @@ function buildSearchParams(obj, prefix = "") {
33
33
  return params;
34
34
  }
35
35
 
36
+ function safeParse(text = "") {
37
+ try {
38
+ /** @type {JsonValue} */
39
+ const body = JSON.parse(text);
40
+ const isJson = true;
41
+
42
+ return { body, isJson };
43
+ } catch {
44
+ return { body: text };
45
+ }
46
+ }
47
+
36
48
  /**
37
49
  *
38
50
  * @param {RequestOptions} requestOptions
@@ -54,6 +66,19 @@ function resolveUrl(requestOptions) {
54
66
  return url;
55
67
  }
56
68
 
69
+ /**
70
+ *
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
77
+ */
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
+ }
81
+
57
82
  /**
58
83
  *
59
84
  * @param {RequestOptions} requestOptions
@@ -148,14 +173,17 @@ function handleRequest(requestOptions, responseHandler) {
148
173
  res.on("data", (chunk) => chunks.push(chunk));
149
174
 
150
175
  res.on("end", () => {
151
- const body = Buffer.concat(chunks).toString();
152
- const msgs = [`Status:${status}`];
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}`);
153
182
 
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}`);
183
+ const msg = verbose.join(" ");
157
184
 
158
- const msg = msgs.join(" ");
185
+ const json = safeParse(text);
186
+ resolve(buildResponse(requestOptions, res, false, json.body, json.isJson, verbose));
159
187
  reject(new Error(msg));
160
188
  });
161
189
 
@@ -180,6 +208,7 @@ function handleRequest(requestOptions, responseHandler) {
180
208
  port: parsed.port,
181
209
  };
182
210
 
211
+ // @ts-ignore
183
212
  const req = isHttps ? https.request(options, cb) : http.request(options, cb);
184
213
 
185
214
  req.setTimeout(timeoutMs, () => {
@@ -214,36 +243,25 @@ async function request(requestOptions) {
214
243
 
215
244
  res.on("end", () => {
216
245
  const text = Buffer.concat(chunks).toString();
246
+ const json = safeParse(text);
217
247
 
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
- });
248
+ resolve(buildResponse(requestOptions, res, true, json.body, json.isJson));
235
249
  });
236
250
  });
237
251
  }
252
+
238
253
  /**
239
254
  *
240
255
  * @param {RequestOptions} requestOptions
256
+ *
257
+ * @returns {Promise<Omit<RequestResponse, 'body'>>}
258
+ *
241
259
  */
242
260
  function requestHeaders(requestOptions) {
243
261
  return handleRequest(requestOptions, (res, resolve) => {
244
262
  res.destroy();
245
263
 
246
- resolve({ status: res.statusCode, headers: res.headers });
264
+ resolve(buildResponse(requestOptions, res));
247
265
  });
248
266
  }
249
267
 
@@ -251,10 +269,15 @@ function requestHeaders(requestOptions) {
251
269
  *
252
270
  * @param {RequestOptions} requestOptions
253
271
  * @param {WriteStream} stream
272
+ *
273
+ * @returns {Promise<Omit<RequestResponse, 'body'>>}
274
+ *
254
275
  */
255
276
  function requestFile(requestOptions, stream) {
256
277
  return handleRequest(requestOptions, (res, resolve, reject) => {
257
- pipeline(res, stream).then(resolve).catch(reject);
278
+ pipeline(res, stream)
279
+ .then(() => resolve(buildResponse(requestOptions, res)))
280
+ .catch(reject);
258
281
  });
259
282
  }
260
283
 
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { IncomingMessage } from "node:http";
1
+ import { IncomingHttpHeaders, IncomingMessage } from "node:http";
2
2
 
3
3
  type SearchParamsValue = string | number | boolean | null | undefined | SearchParamsObject | unknown[];
4
4
 
@@ -19,14 +19,19 @@ export interface RequestOptions {
19
19
 
20
20
  export type RequestHandler = (
21
21
  res: IncomingMessage,
22
- resolve: (value: any) => void,
22
+ resolve: (value: RequestResponse) => void,
23
23
  reject: (err: Error) => void,
24
24
  ) => void;
25
25
 
26
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
27
+
26
28
  export interface RequestResponse {
27
- success: boolean;
28
- isJson: boolean;
29
- body: string | any;
30
- status: string;
29
+ success?: boolean;
30
+ status: number;
31
+ headers: IncomingHttpHeaders;
32
+ body?: JsonValue;
33
+ isJson?: boolean;
31
34
  requestOptions: RequestOptions;
35
+
36
+ verbose?: string[];
32
37
  }