@faasjs/request 0.0.3-beta.99 → 0.0.4-beta.10

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
@@ -54,7 +54,8 @@ ___
54
54
  | `agent?` | `boolean` | - |
55
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. ```ts const stream = createWriteStream('filepath') await request('https://example.com', { downloadStream: stream }) ``` |
57
+ | `downloadFile?` | `string` | Path of downloading a file from the server. ```ts await request('https://example.com', { downloadFile: 'filepath' }) ``` |
58
+ | `downloadStream?` | `NodeJS.WritableStream` | Create a write stream to download a file. ```ts import { createWriteStream } from 'fs' const stream = createWriteStream('filepath') await request('https://example.com', { downloadStream: stream }) ``` |
58
59
  | `file?` | `string` | Path of uploading a file to the server. ```ts await request('https://example.com', { file: 'filepath' }) ``` |
59
60
  | `headers?` | `http.OutgoingHttpHeaders` | - |
60
61
  | `logger?` | `Logger` | - |
@@ -111,10 +112,6 @@ ___
111
112
 
112
113
  Request
113
114
 
114
- **`Url`**
115
-
116
- https://faasjs.com/doc/request.html
117
-
118
115
  #### Type parameters
119
116
 
120
117
  | Name | Type |
@@ -132,6 +129,10 @@ https://faasjs.com/doc/request.html
132
129
 
133
130
  `Promise`<[`Response`](#response)<`T`\>\>
134
131
 
132
+ **`Url`**
133
+
134
+ https://faasjs.com/doc/request.html
135
+
135
136
  ___
136
137
 
137
138
  ### setMock
@@ -140,12 +141,6 @@ ___
140
141
 
141
142
  Mock requests
142
143
 
143
- **`Example`**
144
-
145
- ```ts
146
- setMock(async (url, options) => Promise.resolve({ headers: {}, statusCode: 200, body: { data: 'ok' } }))
147
- ```
148
-
149
144
  #### Parameters
150
145
 
151
146
  | Name | Type | Description |
@@ -155,3 +150,9 @@ setMock(async (url, options) => Promise.resolve({ headers: {}, statusCode: 200,
155
150
  #### Returns
156
151
 
157
152
  `void`
153
+
154
+ **`Example`**
155
+
156
+ ```ts
157
+ setMock(async (url, options) => Promise.resolve({ headers: {}, statusCode: 200, body: { data: 'ok' } }))
158
+ ```
package/dist/index.d.mts CHANGED
@@ -49,11 +49,21 @@ type RequestOptions = {
49
49
  * Create a write stream to download a file.
50
50
  *
51
51
  * ```ts
52
+ * import { createWriteStream } from 'fs'
53
+ *
52
54
  * const stream = createWriteStream('filepath')
53
55
  * await request('https://example.com', { downloadStream: stream })
54
56
  * ```
55
57
  */
56
58
  downloadStream?: NodeJS.WritableStream;
59
+ /**
60
+ * Path of downloading a file from the server.
61
+ *
62
+ * ```ts
63
+ * await request('https://example.com', { downloadFile: 'filepath' })
64
+ * ```
65
+ */
66
+ downloadFile?: string;
57
67
  pfx?: Buffer;
58
68
  passphrase?: string;
59
69
  agent?: boolean;
@@ -71,8 +81,21 @@ type Mock = (url: string, options: RequestOptions) => Promise<Response>;
71
81
  */
72
82
  declare function setMock(handler: Mock | null): void;
73
83
  declare function querystringify(obj: any): string;
84
+ /**
85
+ * ResponseError class
86
+ */
87
+ declare class ResponseError extends Error {
88
+ response: Response;
89
+ request: Request;
90
+ statusCode: number;
91
+ statusMessage: string;
92
+ headers: http.OutgoingHttpHeaders;
93
+ body: any;
94
+ constructor(message: string, response: Response<any>);
95
+ }
74
96
  /**
75
97
  * Request
98
+ *
76
99
  * @param {string} url Url
77
100
  * @param {object=} [options={}] Options
78
101
  * @param {string} [options.method=GET] Method
@@ -83,14 +106,16 @@ declare function querystringify(obj: any): string;
83
106
  * @param {string=} options.auth Auth, format: user:password
84
107
  * @param {string=} options.file Upload file path
85
108
  * @param {WritableStream=} options.downloadStream Download stream
109
+ * @param {string=} options.downloadFile Download to file
86
110
  * @param {Buffer=} options.pfx pfx
87
111
  * @param {string=} options.passphrase passphrase
88
112
  * @param {boolean=} options.agent agent
89
113
  * @param {parse=} options.parse body parser, default is JSON.parse
90
114
  *
91
115
  * @returns {promise}
116
+ *
92
117
  * @url https://faasjs.com/doc/request.html
93
118
  */
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>>;
119
+ declare function request<T = any>(url: string, { headers, method, query, body, timeout, auth, file, downloadStream, downloadFile, pfx, passphrase, agent, parse, logger, }?: RequestOptions): Promise<Response<T>>;
95
120
 
96
- export { Request, RequestOptions, Response, querystringify, request, setMock };
121
+ export { Request, RequestOptions, Response, ResponseError, querystringify, request, setMock };
package/dist/index.d.ts CHANGED
@@ -49,11 +49,21 @@ type RequestOptions = {
49
49
  * Create a write stream to download a file.
50
50
  *
51
51
  * ```ts
52
+ * import { createWriteStream } from 'fs'
53
+ *
52
54
  * const stream = createWriteStream('filepath')
53
55
  * await request('https://example.com', { downloadStream: stream })
54
56
  * ```
55
57
  */
56
58
  downloadStream?: NodeJS.WritableStream;
59
+ /**
60
+ * Path of downloading a file from the server.
61
+ *
62
+ * ```ts
63
+ * await request('https://example.com', { downloadFile: 'filepath' })
64
+ * ```
65
+ */
66
+ downloadFile?: string;
57
67
  pfx?: Buffer;
58
68
  passphrase?: string;
59
69
  agent?: boolean;
@@ -71,8 +81,21 @@ type Mock = (url: string, options: RequestOptions) => Promise<Response>;
71
81
  */
72
82
  declare function setMock(handler: Mock | null): void;
73
83
  declare function querystringify(obj: any): string;
84
+ /**
85
+ * ResponseError class
86
+ */
87
+ declare class ResponseError extends Error {
88
+ response: Response;
89
+ request: Request;
90
+ statusCode: number;
91
+ statusMessage: string;
92
+ headers: http.OutgoingHttpHeaders;
93
+ body: any;
94
+ constructor(message: string, response: Response<any>);
95
+ }
74
96
  /**
75
97
  * Request
98
+ *
76
99
  * @param {string} url Url
77
100
  * @param {object=} [options={}] Options
78
101
  * @param {string} [options.method=GET] Method
@@ -83,14 +106,16 @@ declare function querystringify(obj: any): string;
83
106
  * @param {string=} options.auth Auth, format: user:password
84
107
  * @param {string=} options.file Upload file path
85
108
  * @param {WritableStream=} options.downloadStream Download stream
109
+ * @param {string=} options.downloadFile Download to file
86
110
  * @param {Buffer=} options.pfx pfx
87
111
  * @param {string=} options.passphrase passphrase
88
112
  * @param {boolean=} options.agent agent
89
113
  * @param {parse=} options.parse body parser, default is JSON.parse
90
114
  *
91
115
  * @returns {promise}
116
+ *
92
117
  * @url https://faasjs.com/doc/request.html
93
118
  */
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>>;
119
+ declare function request<T = any>(url: string, { headers, method, query, body, timeout, auth, file, downloadStream, downloadFile, pfx, passphrase, agent, parse, logger, }?: RequestOptions): Promise<Response<T>>;
95
120
 
96
- export { Request, RequestOptions, Response, querystringify, request, setMock };
121
+ export { Request, RequestOptions, Response, ResponseError, querystringify, request, setMock };
package/dist/index.js CHANGED
@@ -40,18 +40,29 @@ function querystringify(obj) {
40
40
  for (key in obj) {
41
41
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
42
42
  value = obj[key];
43
- if (!value && (value === null || value === void 0 || isNaN(value))) {
43
+ if (!value && (value === null || value === void 0 || Number.isNaN(value))) {
44
44
  value = "";
45
45
  }
46
46
  key = encodeURIComponent(key);
47
47
  value = encodeURIComponent(value);
48
48
  if (key === null || value === null)
49
49
  continue;
50
- pairs.push(key + "=" + value);
50
+ pairs.push(`${key}=${value}`);
51
51
  }
52
52
  }
53
53
  return pairs.length ? pairs.join("&") : "";
54
54
  }
55
+ var ResponseError = class extends Error {
56
+ constructor(message, response) {
57
+ super(message);
58
+ this.response = response;
59
+ this.request = response.request;
60
+ this.statusCode = response.statusCode;
61
+ this.statusMessage = response.statusMessage;
62
+ this.headers = response.headers;
63
+ this.body = response.body;
64
+ }
65
+ };
55
66
  async function request(url$1, {
56
67
  headers,
57
68
  method,
@@ -61,12 +72,14 @@ async function request(url$1, {
61
72
  auth,
62
73
  file,
63
74
  downloadStream,
75
+ downloadFile,
64
76
  pfx,
65
77
  passphrase,
66
78
  agent,
67
79
  parse,
68
80
  logger: logger$1
69
81
  } = { headers: {} }) {
82
+ var _a;
70
83
  if (!logger$1)
71
84
  logger$1 = new logger.Logger("request");
72
85
  if (mock) {
@@ -99,7 +112,7 @@ async function request(url$1, {
99
112
  host: uri.host ? uri.host.replace(/:[0-9]+$/, "") : uri.host,
100
113
  method: method ? method.toUpperCase() : "GET",
101
114
  path: uri.pathname + uri.search,
102
- port: uri.port,
115
+ port: uri.port || (uri.protocol === "https:" ? "443" : "80"),
103
116
  timeout,
104
117
  auth,
105
118
  pfx,
@@ -110,7 +123,7 @@ async function request(url$1, {
110
123
  if (typeof headers[key] !== "undefined" && headers[key] !== null)
111
124
  options.headers[key] = headers[key];
112
125
  if (body && typeof body !== "string")
113
- if (options.headers["Content-Type"] && options.headers["Content-Type"].toString().includes("application/x-www-form-urlencoded"))
126
+ if ((_a = options.headers["Content-Type"]) == null ? void 0 : _a.toString().includes("application/x-www-form-urlencoded"))
114
127
  body = querystringify(body);
115
128
  else
116
129
  body = JSON.stringify(body);
@@ -124,9 +137,11 @@ async function request(url$1, {
124
137
  const req = protocol.request(options, function(res) {
125
138
  if (downloadStream) {
126
139
  res.pipe(downloadStream);
127
- downloadStream.on("finish", function() {
128
- resolve(void 0);
129
- });
140
+ downloadStream.on("finish", () => resolve(void 0));
141
+ } else if (downloadFile) {
142
+ const stream = fs.createWriteStream(downloadFile);
143
+ res.pipe(stream);
144
+ stream.on("finish", () => resolve(void 0));
130
145
  } else {
131
146
  const raw = [];
132
147
  res.on("data", (chunk) => {
@@ -134,8 +149,14 @@ async function request(url$1, {
134
149
  });
135
150
  res.on("end", () => {
136
151
  const data = Buffer.concat(raw).toString();
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();
152
+ logger$1.timeEnd(
153
+ url$1,
154
+ "response %s %s %s",
155
+ res.statusCode,
156
+ res.headers["content-type"],
157
+ data
158
+ );
159
+ const response = /* @__PURE__ */ Object.create(null);
139
160
  response.request = options;
140
161
  response.request.body = body;
141
162
  response.statusCode = res.statusCode;
@@ -154,8 +175,12 @@ async function request(url$1, {
154
175
  resolve(response);
155
176
  else {
156
177
  logger$1.debug("response.error %j", response);
157
- response.message = `${res.statusMessage || res.statusCode} ${options.host}${options.path}`;
158
- reject(response);
178
+ reject(
179
+ new ResponseError(
180
+ `${res.statusMessage || res.statusCode} ${options.host}${options.path}`,
181
+ response
182
+ )
183
+ );
159
184
  }
160
185
  });
161
186
  }
@@ -166,13 +191,17 @@ async function request(url$1, {
166
191
  const crlf = "\r\n";
167
192
  const boundary = `--${Math.random().toString(16)}`;
168
193
  const delimiter = `${crlf}--${boundary}`;
169
- const headers2 = [`Content-Disposition: form-data; name="file"; filename="${path.basename(file)}"${crlf}`];
194
+ const headers2 = [
195
+ `Content-Disposition: form-data; name="file"; filename="${path.basename(
196
+ file
197
+ )}"${crlf}`
198
+ ];
170
199
  const multipartBody = Buffer.concat([
171
200
  Buffer.from(delimiter + crlf + headers2.join("") + crlf),
172
201
  fs.readFileSync(file),
173
202
  Buffer.from(`${delimiter}--`)
174
203
  ]);
175
- req.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
204
+ req.setHeader("Content-Type", `multipart/form-data; boundary=${boundary}`);
176
205
  req.setHeader("Content-Length", multipartBody.length);
177
206
  req.write(multipartBody);
178
207
  }
@@ -185,6 +214,7 @@ async function request(url$1, {
185
214
  });
186
215
  }
187
216
 
217
+ exports.ResponseError = ResponseError;
188
218
  exports.querystringify = querystringify;
189
219
  exports.request = request;
190
220
  exports.setMock = setMock;
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as http from 'http';
2
2
  import * as https from 'https';
3
3
  import { URL } from 'url';
4
- import { readFileSync } from 'fs';
4
+ import { createWriteStream, readFileSync } from 'fs';
5
5
  import { basename } from 'path';
6
6
  import { Logger } from '@faasjs/logger';
7
7
 
@@ -17,18 +17,29 @@ function querystringify(obj) {
17
17
  for (key in obj) {
18
18
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
19
19
  value = obj[key];
20
- if (!value && (value === null || value === void 0 || isNaN(value))) {
20
+ if (!value && (value === null || value === void 0 || Number.isNaN(value))) {
21
21
  value = "";
22
22
  }
23
23
  key = encodeURIComponent(key);
24
24
  value = encodeURIComponent(value);
25
25
  if (key === null || value === null)
26
26
  continue;
27
- pairs.push(key + "=" + value);
27
+ pairs.push(`${key}=${value}`);
28
28
  }
29
29
  }
30
30
  return pairs.length ? pairs.join("&") : "";
31
31
  }
32
+ var ResponseError = class extends Error {
33
+ constructor(message, response) {
34
+ super(message);
35
+ this.response = response;
36
+ this.request = response.request;
37
+ this.statusCode = response.statusCode;
38
+ this.statusMessage = response.statusMessage;
39
+ this.headers = response.headers;
40
+ this.body = response.body;
41
+ }
42
+ };
32
43
  async function request(url, {
33
44
  headers,
34
45
  method,
@@ -38,12 +49,14 @@ async function request(url, {
38
49
  auth,
39
50
  file,
40
51
  downloadStream,
52
+ downloadFile,
41
53
  pfx,
42
54
  passphrase,
43
55
  agent,
44
56
  parse,
45
57
  logger
46
58
  } = { headers: {} }) {
59
+ var _a;
47
60
  if (!logger)
48
61
  logger = new Logger("request");
49
62
  if (mock) {
@@ -76,7 +89,7 @@ async function request(url, {
76
89
  host: uri.host ? uri.host.replace(/:[0-9]+$/, "") : uri.host,
77
90
  method: method ? method.toUpperCase() : "GET",
78
91
  path: uri.pathname + uri.search,
79
- port: uri.port,
92
+ port: uri.port || (uri.protocol === "https:" ? "443" : "80"),
80
93
  timeout,
81
94
  auth,
82
95
  pfx,
@@ -87,7 +100,7 @@ async function request(url, {
87
100
  if (typeof headers[key] !== "undefined" && headers[key] !== null)
88
101
  options.headers[key] = headers[key];
89
102
  if (body && typeof body !== "string")
90
- if (options.headers["Content-Type"] && options.headers["Content-Type"].toString().includes("application/x-www-form-urlencoded"))
103
+ if ((_a = options.headers["Content-Type"]) == null ? void 0 : _a.toString().includes("application/x-www-form-urlencoded"))
91
104
  body = querystringify(body);
92
105
  else
93
106
  body = JSON.stringify(body);
@@ -101,9 +114,11 @@ async function request(url, {
101
114
  const req = protocol.request(options, function(res) {
102
115
  if (downloadStream) {
103
116
  res.pipe(downloadStream);
104
- downloadStream.on("finish", function() {
105
- resolve(void 0);
106
- });
117
+ downloadStream.on("finish", () => resolve(void 0));
118
+ } else if (downloadFile) {
119
+ const stream = createWriteStream(downloadFile);
120
+ res.pipe(stream);
121
+ stream.on("finish", () => resolve(void 0));
107
122
  } else {
108
123
  const raw = [];
109
124
  res.on("data", (chunk) => {
@@ -111,8 +126,14 @@ async function request(url, {
111
126
  });
112
127
  res.on("end", () => {
113
128
  const data = Buffer.concat(raw).toString();
114
- logger.timeEnd(url, "response %s %s %s", res.statusCode, res.headers["content-type"], data);
115
- const response = res.statusCode >= 200 && res.statusCode < 400 ? /* @__PURE__ */ Object.create(null) : new Error();
129
+ logger.timeEnd(
130
+ url,
131
+ "response %s %s %s",
132
+ res.statusCode,
133
+ res.headers["content-type"],
134
+ data
135
+ );
136
+ const response = /* @__PURE__ */ Object.create(null);
116
137
  response.request = options;
117
138
  response.request.body = body;
118
139
  response.statusCode = res.statusCode;
@@ -131,8 +152,12 @@ async function request(url, {
131
152
  resolve(response);
132
153
  else {
133
154
  logger.debug("response.error %j", response);
134
- response.message = `${res.statusMessage || res.statusCode} ${options.host}${options.path}`;
135
- reject(response);
155
+ reject(
156
+ new ResponseError(
157
+ `${res.statusMessage || res.statusCode} ${options.host}${options.path}`,
158
+ response
159
+ )
160
+ );
136
161
  }
137
162
  });
138
163
  }
@@ -143,13 +168,17 @@ async function request(url, {
143
168
  const crlf = "\r\n";
144
169
  const boundary = `--${Math.random().toString(16)}`;
145
170
  const delimiter = `${crlf}--${boundary}`;
146
- const headers2 = [`Content-Disposition: form-data; name="file"; filename="${basename(file)}"${crlf}`];
171
+ const headers2 = [
172
+ `Content-Disposition: form-data; name="file"; filename="${basename(
173
+ file
174
+ )}"${crlf}`
175
+ ];
147
176
  const multipartBody = Buffer.concat([
148
177
  Buffer.from(delimiter + crlf + headers2.join("") + crlf),
149
178
  readFileSync(file),
150
179
  Buffer.from(`${delimiter}--`)
151
180
  ]);
152
- req.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
181
+ req.setHeader("Content-Type", `multipart/form-data; boundary=${boundary}`);
153
182
  req.setHeader("Content-Length", multipartBody.length);
154
183
  req.write(multipartBody);
155
184
  }
@@ -162,4 +191,4 @@ async function request(url, {
162
191
  });
163
192
  }
164
193
 
165
- export { querystringify, request, setMock };
194
+ export { ResponseError, querystringify, request, setMock };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faasjs/request",
3
- "version": "0.0.3-beta.99",
3
+ "version": "0.0.4-beta.10",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -20,11 +20,14 @@
20
20
  "files": [
21
21
  "dist"
22
22
  ],
23
- "dependencies": {
24
- "@faasjs/logger": "0.0.3-beta.99"
23
+ "peerDependencies": {
24
+ "@faasjs/logger": "0.0.4-beta.10"
25
+ },
26
+ "devDependencies": {
27
+ "@faasjs/logger": "0.0.4-beta.10"
25
28
  },
26
29
  "engines": {
27
- "npm": ">=8.0.0",
28
- "node": ">=16.0.0"
30
+ "npm": ">=9.0.0",
31
+ "node": ">=18.0.0"
29
32
  }
30
33
  }