@faasjs/request 0.0.3-beta.9 → 0.0.3-beta.91

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/README.md CHANGED
@@ -52,10 +52,10 @@ ___
52
52
  | Name | Type | Description |
53
53
  | :------ | :------ | :------ |
54
54
  | `agent?` | `boolean` | - |
55
- | `auth?` | `string` | The authentication credentials to use for the request. Format: `username:password` |
55
+ | `auth?` | `string` | The authentication credentials to use for the request. Format: `username:password` |
56
56
  | `body?` | { `[key: string]`: `any`; } \| `string` | - |
57
- | `downloadStream?` | `NodeJS.WritableStream` | Create a write stream to download a file. |
58
- | `file?` | `string` | Path of uploading a file to the server. |
57
+ | `downloadStream?` | `NodeJS.WritableStream` | Create a write stream to download a file. ```ts const stream = createWriteStream('filepath') await request('https://example.com', { downloadStream: stream }) ``` |
58
+ | `file?` | `string` | Path of uploading a file to the server. ```ts await request('https://example.com', { file: 'filepath' }) ``` |
59
59
  | `headers?` | `http.OutgoingHttpHeaders` | - |
60
60
  | `logger?` | `Logger` | - |
61
61
  | `method?` | `string` | The HTTP method to use when making the request. Defaults to GET. |
@@ -0,0 +1,96 @@
1
+ import * as http from 'http';
2
+ import { Logger } from '@faasjs/logger';
3
+
4
+ type Request = {
5
+ headers?: http.OutgoingHttpHeaders;
6
+ method?: string;
7
+ host?: string;
8
+ path?: string;
9
+ query?: http.OutgoingHttpHeaders;
10
+ body?: {
11
+ [key: string]: any;
12
+ };
13
+ };
14
+ type Response<T = any> = {
15
+ request?: Request;
16
+ statusCode?: number;
17
+ statusMessage?: string;
18
+ headers: http.OutgoingHttpHeaders;
19
+ body: T;
20
+ };
21
+ type RequestOptions = {
22
+ headers?: http.OutgoingHttpHeaders;
23
+ /**
24
+ * The HTTP method to use when making the request. Defaults to GET.
25
+ */
26
+ method?: string;
27
+ query?: {
28
+ [key: string]: any;
29
+ };
30
+ body?: {
31
+ [key: string]: any;
32
+ } | string;
33
+ timeout?: number;
34
+ /**
35
+ * The authentication credentials to use for the request.
36
+ *
37
+ * Format: `username:password`
38
+ */
39
+ auth?: string;
40
+ /**
41
+ * Path of uploading a file to the server.
42
+ *
43
+ * ```ts
44
+ * await request('https://example.com', { file: 'filepath' })
45
+ * ```
46
+ */
47
+ file?: string;
48
+ /**
49
+ * Create a write stream to download a file.
50
+ *
51
+ * ```ts
52
+ * const stream = createWriteStream('filepath')
53
+ * await request('https://example.com', { downloadStream: stream })
54
+ * ```
55
+ */
56
+ downloadStream?: NodeJS.WritableStream;
57
+ pfx?: Buffer;
58
+ passphrase?: string;
59
+ agent?: boolean;
60
+ /**
61
+ * Body parser. Defaults to `JSON.parse`.
62
+ */
63
+ parse?: (body: string) => any;
64
+ logger?: Logger;
65
+ };
66
+ type Mock = (url: string, options: RequestOptions) => Promise<Response>;
67
+ /**
68
+ * Mock requests
69
+ * @param handler {function | null} null to disable mock
70
+ * @example setMock(async (url, options) => Promise.resolve({ headers: {}, statusCode: 200, body: { data: 'ok' } }))
71
+ */
72
+ declare function setMock(handler: Mock | null): void;
73
+ declare function querystringify(obj: any): string;
74
+ /**
75
+ * Request
76
+ * @param {string} url Url
77
+ * @param {object=} [options={}] Options
78
+ * @param {string} [options.method=GET] Method
79
+ * @param {object} [options.query={}] Query
80
+ * @param {object} [options.headers={}] Headers
81
+ * @param {object=} options.body Body
82
+ * @param {number=} options.timeout Timeout
83
+ * @param {string=} options.auth Auth, format: user:password
84
+ * @param {string=} options.file Upload file path
85
+ * @param {WritableStream=} options.downloadStream Download stream
86
+ * @param {Buffer=} options.pfx pfx
87
+ * @param {string=} options.passphrase passphrase
88
+ * @param {boolean=} options.agent agent
89
+ * @param {parse=} options.parse body parser, default is JSON.parse
90
+ *
91
+ * @returns {promise}
92
+ * @url https://faasjs.com/doc/request.html
93
+ */
94
+ declare function request<T = any>(url: string, { headers, method, query, body, timeout, auth, file, downloadStream, pfx, passphrase, agent, parse, logger, }?: RequestOptions): Promise<Response<T>>;
95
+
96
+ export { Request, RequestOptions, Response, querystringify, request, setMock };
package/dist/index.d.ts CHANGED
@@ -39,10 +39,19 @@ type RequestOptions = {
39
39
  auth?: string;
40
40
  /**
41
41
  * Path of uploading a file to the server.
42
+ *
43
+ * ```ts
44
+ * await request('https://example.com', { file: 'filepath' })
45
+ * ```
42
46
  */
43
47
  file?: string;
44
48
  /**
45
49
  * Create a write stream to download a file.
50
+ *
51
+ * ```ts
52
+ * const stream = createWriteStream('filepath')
53
+ * await request('https://example.com', { downloadStream: stream })
54
+ * ```
46
55
  */
47
56
  downloadStream?: NodeJS.WritableStream;
48
57
  pfx?: Buffer;
package/dist/index.js CHANGED
@@ -1,42 +1,34 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1
+ 'use strict';
2
+
3
+ var http = require('http');
4
+ var https = require('https');
5
+ var url = require('url');
6
+ var fs = require('fs');
7
+ var path = require('path');
8
+ var logger = require('@faasjs/logger');
9
+
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
20
+ });
21
+ }
22
+ });
17
23
  }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+ n.default = e;
25
+ return Object.freeze(n);
26
+ }
27
+
28
+ var http__namespace = /*#__PURE__*/_interopNamespace(http);
29
+ var https__namespace = /*#__PURE__*/_interopNamespace(https);
25
30
 
26
31
  // src/index.ts
27
- var src_exports = {};
28
- __export(src_exports, {
29
- querystringify: () => querystringify,
30
- request: () => request,
31
- setMock: () => setMock
32
- });
33
- module.exports = __toCommonJS(src_exports);
34
- var http = __toESM(require("http"));
35
- var https = __toESM(require("https"));
36
- var import_url = require("url");
37
- var import_fs = require("fs");
38
- var import_path = require("path");
39
- var import_logger = require("@faasjs/logger");
40
32
  var mock = null;
41
33
  function setMock(handler) {
42
34
  mock = handler;
@@ -60,7 +52,7 @@ function querystringify(obj) {
60
52
  }
61
53
  return pairs.length ? pairs.join("&") : "";
62
54
  }
63
- async function request(url, {
55
+ async function request(url$1, {
64
56
  headers,
65
57
  method,
66
58
  query,
@@ -73,26 +65,33 @@ async function request(url, {
73
65
  passphrase,
74
66
  agent,
75
67
  parse,
76
- logger
68
+ logger: logger$1
77
69
  } = { headers: {} }) {
78
- if (!logger)
79
- logger = new import_logger.Logger("request");
80
- if (mock)
81
- return mock(url, {
70
+ if (!logger$1)
71
+ logger$1 = new logger.Logger("request");
72
+ if (mock) {
73
+ logger$1.debug("mock %s %j", url$1, {
82
74
  headers,
83
75
  method,
84
76
  query,
85
77
  body
86
78
  });
79
+ return mock(url$1, {
80
+ headers,
81
+ method,
82
+ query,
83
+ body
84
+ });
85
+ }
87
86
  if (query) {
88
- if (!url.includes("?"))
89
- url += "?";
90
- else if (!url.endsWith("?"))
91
- url += "&";
92
- url += querystringify(query);
87
+ if (!url$1.includes("?"))
88
+ url$1 += "?";
89
+ else if (!url$1.endsWith("?"))
90
+ url$1 += "&";
91
+ url$1 += querystringify(query);
93
92
  }
94
- const uri = new import_url.URL(url);
95
- const protocol = uri.protocol === "https:" ? https : http;
93
+ const uri = new url.URL(url$1);
94
+ const protocol = uri.protocol === "https:" ? https__namespace : http__namespace;
96
95
  if (!uri.protocol)
97
96
  throw Error("Unknown protocol");
98
97
  const options = {
@@ -118,7 +117,7 @@ async function request(url, {
118
117
  if (body && !options.headers["Content-Length"])
119
118
  options.headers["Content-Length"] = Buffer.byteLength(body);
120
119
  return await new Promise(function(resolve, reject) {
121
- logger.debug("request %j", {
120
+ logger$1.debug("request %j", {
122
121
  ...options,
123
122
  body
124
123
  });
@@ -135,8 +134,8 @@ async function request(url, {
135
134
  });
136
135
  res.on("end", () => {
137
136
  const data = Buffer.concat(raw).toString();
138
- logger.timeEnd(url, "response %s %s %s", res.statusCode, res.headers["content-type"], data);
139
- const response = /* @__PURE__ */ Object.create(null);
137
+ logger$1.timeEnd(url$1, "response %s %s %s", res.statusCode, res.headers["content-type"], data);
138
+ const response = res.statusCode >= 200 && res.statusCode < 400 ? /* @__PURE__ */ Object.create(null) : new Error();
140
139
  response.request = options;
141
140
  response.request.body = body;
142
141
  response.statusCode = res.statusCode;
@@ -145,8 +144,8 @@ async function request(url, {
145
144
  response.body = data;
146
145
  if (response.body && response.headers["content-type"] && response.headers["content-type"].includes("application/json"))
147
146
  try {
148
- response.body = parse ? parse(response.body) : JSON.parse(response.body);
149
- logger.debug("response.parse JSON");
147
+ response.body = (parse || JSON.parse)(response.body);
148
+ logger$1.debug("response.parse JSON");
150
149
  } catch (error) {
151
150
  console.warn("response plain body", response.body);
152
151
  console.error(error);
@@ -154,7 +153,8 @@ async function request(url, {
154
153
  if (response.statusCode >= 200 && response.statusCode < 400)
155
154
  resolve(response);
156
155
  else {
157
- logger.debug("response.error %j", response);
156
+ logger$1.debug("response.error %j", response);
157
+ response.message = `${res.statusMessage || res.statusCode} ${options.host}${options.path}`;
158
158
  reject(response);
159
159
  }
160
160
  });
@@ -166,10 +166,10 @@ async function request(url, {
166
166
  const crlf = "\r\n";
167
167
  const boundary = `--${Math.random().toString(16)}`;
168
168
  const delimiter = `${crlf}--${boundary}`;
169
- const headers2 = [`Content-Disposition: form-data; name="file"; filename="${(0, import_path.basename)(file)}"${crlf}`];
169
+ const headers2 = [`Content-Disposition: form-data; name="file"; filename="${path.basename(file)}"${crlf}`];
170
170
  const multipartBody = Buffer.concat([
171
171
  Buffer.from(delimiter + crlf + headers2.join("") + crlf),
172
- (0, import_fs.readFileSync)(file),
172
+ fs.readFileSync(file),
173
173
  Buffer.from(`${delimiter}--`)
174
174
  ]);
175
175
  req.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
@@ -177,16 +177,14 @@ async function request(url, {
177
177
  req.write(multipartBody);
178
178
  }
179
179
  req.on("error", function(e) {
180
- logger.timeEnd(url, "response.error %j", e);
180
+ logger$1.timeEnd(url$1, "response.error %j", e);
181
181
  reject(e);
182
182
  });
183
- logger.time(url);
183
+ logger$1.time(url$1);
184
184
  req.end();
185
185
  });
186
186
  }
187
- // Annotate the CommonJS export names for ESM import in node:
188
- 0 && (module.exports = {
189
- querystringify,
190
- request,
191
- setMock
192
- });
187
+
188
+ exports.querystringify = querystringify;
189
+ exports.request = request;
190
+ exports.setMock = setMock;
package/dist/index.mjs CHANGED
@@ -1,10 +1,11 @@
1
+ import * as http from 'http';
2
+ import * as https from 'https';
3
+ import { URL } from 'url';
4
+ import { readFileSync } from 'fs';
5
+ import { basename } from 'path';
6
+ import { Logger } from '@faasjs/logger';
7
+
1
8
  // src/index.ts
2
- import * as http from "http";
3
- import * as https from "https";
4
- import { URL } from "url";
5
- import { readFileSync } from "fs";
6
- import { basename } from "path";
7
- import { Logger } from "@faasjs/logger";
8
9
  var mock = null;
9
10
  function setMock(handler) {
10
11
  mock = handler;
@@ -45,13 +46,20 @@ async function request(url, {
45
46
  } = { headers: {} }) {
46
47
  if (!logger)
47
48
  logger = new Logger("request");
48
- if (mock)
49
+ if (mock) {
50
+ logger.debug("mock %s %j", url, {
51
+ headers,
52
+ method,
53
+ query,
54
+ body
55
+ });
49
56
  return mock(url, {
50
57
  headers,
51
58
  method,
52
59
  query,
53
60
  body
54
61
  });
62
+ }
55
63
  if (query) {
56
64
  if (!url.includes("?"))
57
65
  url += "?";
@@ -104,7 +112,7 @@ async function request(url, {
104
112
  res.on("end", () => {
105
113
  const data = Buffer.concat(raw).toString();
106
114
  logger.timeEnd(url, "response %s %s %s", res.statusCode, res.headers["content-type"], data);
107
- const response = /* @__PURE__ */ Object.create(null);
115
+ const response = res.statusCode >= 200 && res.statusCode < 400 ? /* @__PURE__ */ Object.create(null) : new Error();
108
116
  response.request = options;
109
117
  response.request.body = body;
110
118
  response.statusCode = res.statusCode;
@@ -113,7 +121,7 @@ async function request(url, {
113
121
  response.body = data;
114
122
  if (response.body && response.headers["content-type"] && response.headers["content-type"].includes("application/json"))
115
123
  try {
116
- response.body = parse ? parse(response.body) : JSON.parse(response.body);
124
+ response.body = (parse || JSON.parse)(response.body);
117
125
  logger.debug("response.parse JSON");
118
126
  } catch (error) {
119
127
  console.warn("response plain body", response.body);
@@ -123,6 +131,7 @@ async function request(url, {
123
131
  resolve(response);
124
132
  else {
125
133
  logger.debug("response.error %j", response);
134
+ response.message = `${res.statusMessage || res.statusCode} ${options.host}${options.path}`;
126
135
  reject(response);
127
136
  }
128
137
  });
@@ -152,8 +161,5 @@ async function request(url, {
152
161
  req.end();
153
162
  });
154
163
  }
155
- export {
156
- querystringify,
157
- request,
158
- setMock
159
- };
164
+
165
+ export { querystringify, request, setMock };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faasjs/request",
3
- "version": "0.0.3-beta.9",
3
+ "version": "0.0.3-beta.91",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -15,14 +15,13 @@
15
15
  },
16
16
  "funding": "https://github.com/sponsors/faasjs",
17
17
  "scripts": {
18
- "build": "tsup-node src/index.ts --format esm,cjs",
19
- "build:types": "tsup-node src/index.ts --dts-only"
18
+ "build": "tsup-node src/index.ts --config ../../tsup.config.json"
20
19
  },
21
20
  "files": [
22
21
  "dist"
23
22
  ],
24
23
  "dependencies": {
25
- "@faasjs/logger": "^0.0.3-beta.9"
24
+ "@faasjs/logger": "^0.0.3-beta.91"
26
25
  },
27
26
  "engines": {
28
27
  "npm": ">=8.0.0",