api-def 0.8.5 → 0.9.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.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 James Waterhouse
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2019 James Waterhouse
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,34 +1,34 @@
1
- # [api-def](https://github.com/Censkh/api-def/) · [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Censkh/api-def/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/api-def.svg?style=flat)](https://www.npmjs.com/package/api-def) [![build status](https://img.shields.io/github/workflow/status/censkh/api-def/Node.js%20CI)](https://github.com/Censkh/api-def/actions)
2
-
3
- Typed APIs with middleware support
4
-
5
- API def provides a unified way to type your endpoints allowing for compile time checking of query, body, response and even url parameters
6
-
7
- ``` npm i api-def ```
8
-
9
- - [Documentation](https://censkh.github.io/api-def/)
10
-
11
- ```typescript
12
- import {Api} from "api-def";
13
-
14
- const api = new Api({
15
- baseUrl: "https://my-api/",
16
- name: "My API",
17
- });
18
-
19
- const fetchData = api.endpoint()
20
- .queryOf<{ includeAwesome: boolean; }>()
21
- .responseOf<{ data: {awesome: boolean; } }>()
22
- .build({
23
- id: "fetch_data",
24
- method: "get",
25
- path: "/data"
26
- });
27
-
28
- // calls GET https://my-api/data?includeAwesome=true
29
- const res = await fetchData.submit({
30
- query: {includeAwesome: true}
31
- });
32
-
33
- console.log(res.data); // { data: { awesome: true } }
34
- ```
1
+ # [api-def](https://github.com/Censkh/api-def/) &middot; [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/Censkh/api-def/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/api-def.svg?style=flat)](https://www.npmjs.com/package/api-def) [![build status](https://img.shields.io/github/workflow/status/censkh/api-def/Node.js%20CI)](https://github.com/Censkh/api-def/actions)
2
+
3
+ Typed APIs with middleware support
4
+
5
+ API def provides a unified way to type your endpoints allowing for compile time checking of query, body, response and even url parameters
6
+
7
+ ``` npm i api-def ```
8
+
9
+ - [Documentation](https://censkh.github.io/api-def/)
10
+
11
+ ```typescript
12
+ import {Api} from "api-def";
13
+
14
+ const api = new Api({
15
+ baseUrl: "https://my-api/",
16
+ name: "My API",
17
+ });
18
+
19
+ const fetchData = api.endpoint()
20
+ .queryOf<{ includeAwesome: boolean; }>()
21
+ .responseOf<{ data: {awesome: boolean; } }>()
22
+ .build({
23
+ id: "fetch_data",
24
+ method: "get",
25
+ path: "/data"
26
+ });
27
+
28
+ // calls GET https://my-api/data?includeAwesome=true
29
+ const res = await fetchData.submit({
30
+ query: {includeAwesome: true}
31
+ });
32
+
33
+ console.log(res.data); // { data: { awesome: true } }
34
+ ```
@@ -8,7 +8,9 @@ import { Validation } from "./Validation";
8
8
  export default class RequestContext<R = any, P extends Params | undefined = Params | undefined, Q extends Query | undefined = Query | undefined, B extends Body | undefined = Body | undefined> {
9
9
  readonly id: number;
10
10
  readonly key: string;
11
- readonly computedPath: string;
11
+ private computedPath;
12
+ private computedBaseUrl;
13
+ private computedMethod;
12
14
  readonly stats: RequestContextStats;
13
15
  private readonly host;
14
16
  readonly eventHandlers: RequestEventHandlers<R>;
@@ -19,6 +21,7 @@ export default class RequestContext<R = any, P extends Params | undefined = Para
19
21
  readonly cacheInfo: RequestCacheInfo;
20
22
  cancelled: boolean;
21
23
  readonly computedConfig: ComputedRequestConfig<P, Q, B>;
24
+ private computedRequestUrl;
22
25
  readonly mocking: EndpointMockingConfig<R, P, Q, B> | null | undefined;
23
26
  private parsedBody;
24
27
  readonly validation: Validation<R, P, Q, B>;
@@ -36,5 +39,10 @@ export default class RequestContext<R = any, P extends Params | undefined = Para
36
39
  triggerEvent(eventType: RequestEvent): Promise<EventResult<R> | undefined>;
37
40
  addCanceller(canceler: () => void): void;
38
41
  cancel(): void;
39
- getRequestUrl(): URL;
42
+ get requestUrl(): URL;
43
+ get path(): string;
44
+ updatePath(path: string): void;
45
+ updateBaseUrl(baseUrl: string): void;
46
+ updateMethod(method: RequestMethod): void;
47
+ private generateRequestUrl;
40
48
  }
@@ -51,6 +51,8 @@ var RequestContext = /** @class */ (function () {
51
51
  this.computedConfig = config;
52
52
  Utils.assign({}, this.computedConfig.headers);
53
53
  this.computedPath = computedPath;
54
+ this.computedBaseUrl = host.baseUrl;
55
+ this.computedMethod = host.method;
54
56
  this.key = this.generateKey();
55
57
  this.stats = {
56
58
  attempt: 0,
@@ -61,10 +63,11 @@ var RequestContext = /** @class */ (function () {
61
63
  this.validation = host.validation;
62
64
  this.initMiddleware();
63
65
  this.parseRequestBody();
66
+ this.computedRequestUrl = this.generateRequestUrl();
64
67
  }
65
68
  Object.defineProperty(RequestContext.prototype, "method", {
66
69
  get: function () {
67
- return this.host.method;
70
+ return this.computedMethod;
68
71
  },
69
72
  enumerable: false,
70
73
  configurable: true
@@ -78,7 +81,7 @@ var RequestContext = /** @class */ (function () {
78
81
  });
79
82
  Object.defineProperty(RequestContext.prototype, "baseUrl", {
80
83
  get: function () {
81
- return this.host.baseUrl;
84
+ return this.computedBaseUrl;
82
85
  },
83
86
  enumerable: false,
84
87
  configurable: true
@@ -183,7 +186,32 @@ var RequestContext = /** @class */ (function () {
183
186
  this.canceler();
184
187
  }
185
188
  };
186
- RequestContext.prototype.getRequestUrl = function () {
189
+ Object.defineProperty(RequestContext.prototype, "requestUrl", {
190
+ get: function () {
191
+ return this.computedRequestUrl;
192
+ },
193
+ enumerable: false,
194
+ configurable: true
195
+ });
196
+ Object.defineProperty(RequestContext.prototype, "path", {
197
+ get: function () {
198
+ return this.computedPath;
199
+ },
200
+ enumerable: false,
201
+ configurable: true
202
+ });
203
+ RequestContext.prototype.updatePath = function (path) {
204
+ this.computedPath = path;
205
+ this.computedRequestUrl = this.generateRequestUrl();
206
+ };
207
+ RequestContext.prototype.updateBaseUrl = function (baseUrl) {
208
+ this.computedBaseUrl = baseUrl;
209
+ this.computedRequestUrl = this.generateRequestUrl();
210
+ };
211
+ RequestContext.prototype.updateMethod = function (method) {
212
+ this.computedMethod = method;
213
+ };
214
+ RequestContext.prototype.generateRequestUrl = function () {
187
215
  var path = !this.baseUrl.endsWith("/")
188
216
  ? this.baseUrl + "/"
189
217
  : this.baseUrl;
@@ -4,6 +4,7 @@ import RequestContext from "./RequestContext";
4
4
  export declare const RequestErrorCode: {
5
5
  readonly MISC_UNKNOWN_ERROR: "misc/unknown-error";
6
6
  readonly REQUEST_NETWORK_ERROR: "request/network-error";
7
+ readonly REQUEST_HOST_NAME_NOT_FOUND: "request/host-name-not-found";
7
8
  readonly REQUEST_INVALID_STATUS: "request/invalid-status";
8
9
  readonly REQUEST_INVALID_CONFIG: "request/invalid-config";
9
10
  readonly REQUEST_MISMATCH_RESPONSE_TYPE: "request/mismatch-response-type";
@@ -4,6 +4,7 @@ exports.convertToRequestError = exports.isRequestError = exports.RequestErrorCod
4
4
  exports.RequestErrorCode = {
5
5
  MISC_UNKNOWN_ERROR: "misc/unknown-error",
6
6
  REQUEST_NETWORK_ERROR: "request/network-error",
7
+ REQUEST_HOST_NAME_NOT_FOUND: "request/host-name-not-found",
7
8
  REQUEST_INVALID_STATUS: "request/invalid-status",
8
9
  REQUEST_INVALID_CONFIG: "request/invalid-config",
9
10
  REQUEST_MISMATCH_RESPONSE_TYPE: "request/mismatch-response-type",
@@ -26,12 +27,18 @@ var convertToRequestError = function (config) {
26
27
  isRequestError: true,
27
28
  attempts: context.stats.attempt,
28
29
  request: {
29
- url: context.getRequestUrl().href,
30
+ url: context.requestUrl.href,
30
31
  query: context.computedConfig.queryObject,
31
32
  headers: context.computedConfig.headers,
32
33
  body: body,
33
34
  },
34
35
  });
36
+ try {
37
+ Object.defineProperty(resultError, "message", { value: "Request failed".concat((response === null || response === void 0 ? void 0 : response.status) ? " with status code ".concat(response.status) : "", " [").concat(code, "]: ").concat(resultError.message) });
38
+ }
39
+ catch (e) {
40
+ // ignore
41
+ }
35
42
  delete resultError.config;
36
43
  delete resultError.toJSON;
37
44
  Object.setPrototypeOf(error, Error);
package/cjs/Requester.js CHANGED
@@ -299,21 +299,22 @@ var parseResponse = function (context, response, error) { return __awaiter(void
299
299
  }); };
300
300
  var parseError = function (context, rawError) { return __awaiter(void 0, void 0, void 0, function () {
301
301
  var error, extractedResponse, errorResponse, code, errorInfo;
302
- return __generator(this, function (_a) {
303
- switch (_a.label) {
302
+ var _a;
303
+ return __generator(this, function (_b) {
304
+ switch (_b.label) {
304
305
  case 0:
305
306
  if (!(0, RequestError_1.isRequestError)(rawError)) return [3 /*break*/, 1];
306
307
  error = rawError;
307
308
  return [3 /*break*/, 5];
308
309
  case 1: return [4 /*yield*/, context.backend.extractResponseFromError(rawError)];
309
310
  case 2:
310
- extractedResponse = _a.sent();
311
+ extractedResponse = _b.sent();
311
312
  errorResponse = undefined;
312
313
  if (!(extractedResponse !== undefined)) return [3 /*break*/, 4];
313
314
  return [4 /*yield*/, parseResponse(context, extractedResponse, true)];
314
315
  case 3:
315
- errorResponse = _a.sent();
316
- _a.label = 4;
316
+ errorResponse = _b.sent();
317
+ _b.label = 4;
317
318
  case 4:
318
319
  code = (0, ApiUtils_1.isNetworkError)(rawError) ? RequestError_1.RequestErrorCode.REQUEST_NETWORK_ERROR : RequestError_1.RequestErrorCode.MISC_UNKNOWN_ERROR;
319
320
  if (errorResponse) {
@@ -321,9 +322,14 @@ var parseError = function (context, rawError) { return __awaiter(void 0, void 0,
321
322
  code = RequestError_1.RequestErrorCode.REQUEST_INVALID_STATUS;
322
323
  }
323
324
  }
325
+ else {
326
+ if (rawError.code === "ENOTFOUND" || ((_a = rawError.cause) === null || _a === void 0 ? void 0 : _a.code) === "ENOTFOUND") {
327
+ code = RequestError_1.RequestErrorCode.REQUEST_HOST_NAME_NOT_FOUND;
328
+ }
329
+ }
324
330
  errorInfo = context.backend.getErrorInfo(rawError, errorResponse);
325
331
  error = (0, RequestError_1.convertToRequestError)(__assign({ error: rawError, response: errorResponse, code: code, context: context }, errorInfo));
326
- _a.label = 5;
332
+ _b.label = 5;
327
333
  case 5: return [2 /*return*/, error];
328
334
  }
329
335
  });
@@ -74,7 +74,7 @@ var AxiosRequestBackend = /** @class */ (function () {
74
74
  };
75
75
  AxiosRequestBackend.prototype.makeRequest = function (context) {
76
76
  var computedConfig = context.computedConfig;
77
- var url = context.getRequestUrl();
77
+ var url = context.requestUrl;
78
78
  var canceler = null;
79
79
  var promise = axios({
80
80
  method: context.method,
@@ -54,6 +54,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
54
54
  var Utils = require("../Utils");
55
55
  var Utils_1 = require("../Utils");
56
56
  var ApiUtils_1 = require("../ApiUtils");
57
+ var RequestError_1 = require("../RequestError");
57
58
  var FetchError = /** @class */ (function (_super) {
58
59
  __extends(FetchError, _super);
59
60
  function FetchError() {
@@ -86,54 +87,58 @@ var FetchRequestBackend = /** @class */ (function () {
86
87
  });
87
88
  };
88
89
  FetchRequestBackend.prototype.convertResponse = function (context, response) {
90
+ var _a;
89
91
  return __awaiter(this, void 0, void 0, function () {
90
- var contentType, responseType, _a, data, status, headers, error_1, processedHeaders;
92
+ var status, headers, processedHeaders, convertedResponse, responseType, text, data, error_1;
91
93
  return __generator(this, function (_b) {
92
94
  switch (_b.label) {
93
95
  case 0:
94
- contentType = response.headers.get("Content-Type");
95
- responseType = (0, ApiUtils_1.inferResponseType)(contentType);
96
- if (!!response.__text) return [3 /*break*/, 2];
97
- _a = response;
98
- return [4 /*yield*/, response.clone().text()];
96
+ status = response.status, headers = response.headers;
97
+ processedHeaders = {};
98
+ headers.forEach(function (value, key) {
99
+ processedHeaders[key] = value;
100
+ });
101
+ convertedResponse = {
102
+ __lowercaseHeaders: processedHeaders,
103
+ method: context.method,
104
+ url: response.url,
105
+ data: undefined,
106
+ status: status,
107
+ headers: processedHeaders,
108
+ };
109
+ responseType = (_a = context.responseType) !== null && _a !== void 0 ? _a : (0, ApiUtils_1.inferResponseType)(response.headers.get("Content-Type"));
110
+ _b.label = 1;
99
111
  case 1:
100
- _a.__text = _b.sent();
101
- _b.label = 2;
112
+ _b.trys.push([1, 7, , 8]);
113
+ if (!(responseType === "arraybuffer")) return [3 /*break*/, 3];
114
+ return [4 /*yield*/, response.arrayBuffer()];
102
115
  case 2:
103
- data = response.__text;
104
- status = response.status, headers = response.headers;
105
- _b.label = 3;
116
+ data = _b.sent();
117
+ return [3 /*break*/, 6];
106
118
  case 3:
107
- _b.trys.push([3, 7, , 8]);
108
- if (!(responseType === "arraybuffer")) return [3 /*break*/, 5];
109
- return [4 /*yield*/, response.clone().arrayBuffer()];
119
+ if (!(responseType === "json")) return [3 /*break*/, 5];
120
+ return [4 /*yield*/, response.text()];
110
121
  case 4:
111
- data = _b.sent();
122
+ text = _b.sent();
123
+ data = JSON.parse(text);
112
124
  return [3 /*break*/, 6];
113
125
  case 5:
114
- if (responseType === "json") {
115
- data = JSON.parse(response.__text);
116
- }
126
+ data = response.text();
117
127
  _b.label = 6;
118
128
  case 6: return [3 /*break*/, 8];
119
129
  case 7:
120
130
  error_1 = _b.sent();
121
- throw Object.assign(new Error("[api-def] Invalid '".concat(context.responseType, "' response, got: '").concat(response.__text, "'")), {
122
- response: response,
131
+ throw (0, RequestError_1.convertToRequestError)({
132
+ error: Object.assign(new Error("[api-def] Failed to parse response as '".concat(responseType, "'").concat(text ? ", got: ".concat(text) : "")), {
133
+ cause: error_1,
134
+ }),
135
+ code: RequestError_1.RequestErrorCode.REQUEST_MISMATCH_RESPONSE_TYPE,
136
+ context: context,
137
+ response: convertedResponse,
123
138
  });
124
139
  case 8:
125
- processedHeaders = {};
126
- headers.forEach(function (value, key) {
127
- processedHeaders[key] = value;
128
- });
129
- return [2 /*return*/, {
130
- __lowercaseHeaders: processedHeaders,
131
- method: context.method,
132
- url: response.url,
133
- data: data,
134
- status: status,
135
- headers: processedHeaders,
136
- }];
140
+ convertedResponse.data = data;
141
+ return [2 /*return*/, convertedResponse];
137
142
  }
138
143
  });
139
144
  });
@@ -161,7 +166,7 @@ var FetchRequestBackend = /** @class */ (function () {
161
166
  }
162
167
  return parsedHeaders;
163
168
  }, {});
164
- var url = context.getRequestUrl();
169
+ var url = context.requestUrl;
165
170
  var promise = this.fetch(url.href, {
166
171
  method: context.method.toUpperCase(),
167
172
  body: bodyJsonify ? JSON.stringify(body) : body,
@@ -82,7 +82,7 @@ var MockRequestBackend = /** @class */ (function () {
82
82
  params: (_b = context.computedConfig.params) !== null && _b !== void 0 ? _b : {},
83
83
  query: context.computedConfig.queryObject,
84
84
  headers: (_c = context.computedConfig.headers) !== null && _c !== void 0 ? _c : {},
85
- url: context.getRequestUrl().toString(),
85
+ url: context.requestUrl.toString(),
86
86
  };
87
87
  res = {
88
88
  statusCode: -1,
@@ -140,7 +140,7 @@ var MockRequestBackend = /** @class */ (function () {
140
140
  return parsedHeaders;
141
141
  }, {});
142
142
  return [2 /*return*/, {
143
- url: context.getRequestUrl().href,
143
+ url: context.requestUrl.href,
144
144
  method: context.method,
145
145
  headers: parsedHeaders,
146
146
  data: res.response,
@@ -41,11 +41,10 @@ var log = function (context, type, message, config, objects) {
41
41
  if (typeof config.predicate === "function" && !config.predicate()) {
42
42
  return;
43
43
  }
44
- var computedPath = context.computedPath;
45
44
  var color = COLOR_MAP[type];
46
45
  var timestamp = formatTime(new Date());
47
46
  var args = [
48
- "%cnetwork %c[".concat(context.api.name, "] ").concat(context.method.toUpperCase(), " ").concat(computedPath, " %c").concat(message, " %c@ ").concat(timestamp),
47
+ "%cnetwork %c[".concat(context.api.name, "] ").concat(context.method.toUpperCase(), " ").concat(context.path, " %c").concat(message, " %c@ ").concat(timestamp),
49
48
  "color:gray",
50
49
  "color:auto",
51
50
  "color:".concat(color),
@@ -8,7 +8,9 @@ import { Validation } from "./Validation";
8
8
  export default class RequestContext<R = any, P extends Params | undefined = Params | undefined, Q extends Query | undefined = Query | undefined, B extends Body | undefined = Body | undefined> {
9
9
  readonly id: number;
10
10
  readonly key: string;
11
- readonly computedPath: string;
11
+ private computedPath;
12
+ private computedBaseUrl;
13
+ private computedMethod;
12
14
  readonly stats: RequestContextStats;
13
15
  private readonly host;
14
16
  readonly eventHandlers: RequestEventHandlers<R>;
@@ -19,6 +21,7 @@ export default class RequestContext<R = any, P extends Params | undefined = Para
19
21
  readonly cacheInfo: RequestCacheInfo;
20
22
  cancelled: boolean;
21
23
  readonly computedConfig: ComputedRequestConfig<P, Q, B>;
24
+ private computedRequestUrl;
22
25
  readonly mocking: EndpointMockingConfig<R, P, Q, B> | null | undefined;
23
26
  private parsedBody;
24
27
  readonly validation: Validation<R, P, Q, B>;
@@ -36,5 +39,10 @@ export default class RequestContext<R = any, P extends Params | undefined = Para
36
39
  triggerEvent(eventType: RequestEvent): Promise<EventResult<R> | undefined>;
37
40
  addCanceller(canceler: () => void): void;
38
41
  cancel(): void;
39
- getRequestUrl(): URL;
42
+ get requestUrl(): URL;
43
+ get path(): string;
44
+ updatePath(path: string): void;
45
+ updateBaseUrl(baseUrl: string): void;
46
+ updateMethod(method: RequestMethod): void;
47
+ private generateRequestUrl;
40
48
  }
@@ -22,6 +22,8 @@ export default class RequestContext {
22
22
  this.computedConfig = config;
23
23
  Utils.assign({}, this.computedConfig.headers);
24
24
  this.computedPath = computedPath;
25
+ this.computedBaseUrl = host.baseUrl;
26
+ this.computedMethod = host.method;
25
27
  this.key = this.generateKey();
26
28
  this.stats = {
27
29
  attempt: 0,
@@ -32,15 +34,16 @@ export default class RequestContext {
32
34
  this.validation = host.validation;
33
35
  this.initMiddleware();
34
36
  this.parseRequestBody();
37
+ this.computedRequestUrl = this.generateRequestUrl();
35
38
  }
36
39
  get method() {
37
- return this.host.method;
40
+ return this.computedMethod;
38
41
  }
39
42
  get api() {
40
43
  return this.host.api;
41
44
  }
42
45
  get baseUrl() {
43
- return this.host.baseUrl;
46
+ return this.computedBaseUrl;
44
47
  }
45
48
  get responseType() {
46
49
  return this.host.responseType;
@@ -125,7 +128,24 @@ export default class RequestContext {
125
128
  this.canceler();
126
129
  }
127
130
  }
128
- getRequestUrl() {
131
+ get requestUrl() {
132
+ return this.computedRequestUrl;
133
+ }
134
+ get path() {
135
+ return this.computedPath;
136
+ }
137
+ updatePath(path) {
138
+ this.computedPath = path;
139
+ this.computedRequestUrl = this.generateRequestUrl();
140
+ }
141
+ updateBaseUrl(baseUrl) {
142
+ this.computedBaseUrl = baseUrl;
143
+ this.computedRequestUrl = this.generateRequestUrl();
144
+ }
145
+ updateMethod(method) {
146
+ this.computedMethod = method;
147
+ }
148
+ generateRequestUrl() {
129
149
  let path = !this.baseUrl.endsWith("/")
130
150
  ? this.baseUrl + "/"
131
151
  : this.baseUrl;
@@ -4,6 +4,7 @@ import RequestContext from "./RequestContext";
4
4
  export declare const RequestErrorCode: {
5
5
  readonly MISC_UNKNOWN_ERROR: "misc/unknown-error";
6
6
  readonly REQUEST_NETWORK_ERROR: "request/network-error";
7
+ readonly REQUEST_HOST_NAME_NOT_FOUND: "request/host-name-not-found";
7
8
  readonly REQUEST_INVALID_STATUS: "request/invalid-status";
8
9
  readonly REQUEST_INVALID_CONFIG: "request/invalid-config";
9
10
  readonly REQUEST_MISMATCH_RESPONSE_TYPE: "request/mismatch-response-type";
@@ -1,6 +1,7 @@
1
1
  export const RequestErrorCode = {
2
2
  MISC_UNKNOWN_ERROR: "misc/unknown-error",
3
3
  REQUEST_NETWORK_ERROR: "request/network-error",
4
+ REQUEST_HOST_NAME_NOT_FOUND: "request/host-name-not-found",
4
5
  REQUEST_INVALID_STATUS: "request/invalid-status",
5
6
  REQUEST_INVALID_CONFIG: "request/invalid-config",
6
7
  REQUEST_MISMATCH_RESPONSE_TYPE: "request/mismatch-response-type",
@@ -22,12 +23,18 @@ export const convertToRequestError = (config) => {
22
23
  isRequestError: true,
23
24
  attempts: context.stats.attempt,
24
25
  request: {
25
- url: context.getRequestUrl().href,
26
+ url: context.requestUrl.href,
26
27
  query: context.computedConfig.queryObject,
27
28
  headers: context.computedConfig.headers,
28
29
  body: body,
29
30
  },
30
31
  });
32
+ try {
33
+ Object.defineProperty(resultError, "message", { value: `Request failed${(response === null || response === void 0 ? void 0 : response.status) ? ` with status code ${response.status}` : ""} [${code}]: ${resultError.message}` });
34
+ }
35
+ catch (e) {
36
+ // ignore
37
+ }
31
38
  delete resultError.config;
32
39
  delete resultError.toJSON;
33
40
  Object.setPrototypeOf(error, Error);
package/esm/Requester.js CHANGED
@@ -224,6 +224,7 @@ const parseResponse = (context, response, error) => __awaiter(void 0, void 0, vo
224
224
  return response;
225
225
  });
226
226
  const parseError = (context, rawError) => __awaiter(void 0, void 0, void 0, function* () {
227
+ var _e;
227
228
  let error;
228
229
  if (isRequestError(rawError)) {
229
230
  error = rawError;
@@ -240,6 +241,11 @@ const parseError = (context, rawError) => __awaiter(void 0, void 0, void 0, func
240
241
  code = RequestErrorCode.REQUEST_INVALID_STATUS;
241
242
  }
242
243
  }
244
+ else {
245
+ if (rawError.code === "ENOTFOUND" || ((_e = rawError.cause) === null || _e === void 0 ? void 0 : _e.code) === "ENOTFOUND") {
246
+ code = RequestErrorCode.REQUEST_HOST_NAME_NOT_FOUND;
247
+ }
248
+ }
243
249
  const errorInfo = context.backend.getErrorInfo(rawError, errorResponse);
244
250
  error = convertToRequestError(Object.assign({ error: rawError, response: errorResponse, code: code, context: context }, errorInfo));
245
251
  }
@@ -39,7 +39,7 @@ export default class AxiosRequestBackend {
39
39
  }
40
40
  makeRequest(context) {
41
41
  const { computedConfig } = context;
42
- const url = context.getRequestUrl();
42
+ const url = context.requestUrl;
43
43
  let canceler = null;
44
44
  const promise = axios({
45
45
  method: context.method,
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import * as Utils from "../Utils";
11
11
  import { getGlobal, getGlobalFetch } from "../Utils";
12
12
  import { inferResponseType } from "../ApiUtils";
13
+ import { convertToRequestError, RequestErrorCode } from "../RequestError";
13
14
  class FetchError extends Error {
14
15
  }
15
16
  export default class FetchRequestBackend {
@@ -34,39 +35,48 @@ export default class FetchRequestBackend {
34
35
  });
35
36
  }
36
37
  convertResponse(context, response) {
38
+ var _a;
37
39
  return __awaiter(this, void 0, void 0, function* () {
38
- const contentType = response.headers.get("Content-Type");
39
- const responseType = inferResponseType(contentType);
40
- if (!response.__text) {
41
- response.__text = yield response.clone().text();
42
- }
43
- let data = response.__text;
44
40
  const { status, headers } = response;
45
- try {
46
- if (responseType === "arraybuffer") {
47
- data = yield response.clone().arrayBuffer();
48
- }
49
- else if (responseType === "json") {
50
- data = JSON.parse(response.__text);
51
- }
52
- }
53
- catch (error) {
54
- throw Object.assign(new Error(`[api-def] Invalid '${context.responseType}' response, got: '${response.__text}'`), {
55
- response,
56
- });
57
- }
58
41
  const processedHeaders = {};
59
42
  headers.forEach((value, key) => {
60
43
  processedHeaders[key] = value;
61
44
  });
62
- return {
45
+ const convertedResponse = {
63
46
  __lowercaseHeaders: processedHeaders,
64
47
  method: context.method,
65
48
  url: response.url,
66
- data: data,
49
+ data: undefined,
67
50
  status: status,
68
51
  headers: processedHeaders,
69
52
  };
53
+ const responseType = (_a = context.responseType) !== null && _a !== void 0 ? _a : inferResponseType(response.headers.get("Content-Type"));
54
+ let text;
55
+ let data;
56
+ try {
57
+ if (responseType === "arraybuffer") {
58
+ data = yield response.arrayBuffer();
59
+ }
60
+ else if (responseType === "json") {
61
+ text = yield response.text();
62
+ data = JSON.parse(text);
63
+ }
64
+ else {
65
+ data = response.text();
66
+ }
67
+ }
68
+ catch (error) {
69
+ throw convertToRequestError({
70
+ error: Object.assign(new Error(`[api-def] Failed to parse response as '${responseType}'${text ? `, got: ${text}` : ""}`), {
71
+ cause: error,
72
+ }),
73
+ code: RequestErrorCode.REQUEST_MISMATCH_RESPONSE_TYPE,
74
+ context: context,
75
+ response: convertedResponse,
76
+ });
77
+ }
78
+ convertedResponse.data = data;
79
+ return convertedResponse;
70
80
  });
71
81
  }
72
82
  makeRequest(context) {
@@ -92,7 +102,7 @@ export default class FetchRequestBackend {
92
102
  }
93
103
  return parsedHeaders;
94
104
  }, {});
95
- const url = context.getRequestUrl();
105
+ const url = context.requestUrl;
96
106
  const promise = this.fetch(url.href, {
97
107
  method: context.method.toUpperCase(),
98
108
  body: bodyJsonify ? JSON.stringify(body) : body,
@@ -44,7 +44,7 @@ export default class MockRequestBackend {
44
44
  params: (_b = context.computedConfig.params) !== null && _b !== void 0 ? _b : {},
45
45
  query: context.computedConfig.queryObject,
46
46
  headers: (_c = context.computedConfig.headers) !== null && _c !== void 0 ? _c : {},
47
- url: context.getRequestUrl().toString(),
47
+ url: context.requestUrl.toString(),
48
48
  };
49
49
  const res = {
50
50
  statusCode: -1,
@@ -96,7 +96,7 @@ export default class MockRequestBackend {
96
96
  return parsedHeaders;
97
97
  }, {});
98
98
  return {
99
- url: context.getRequestUrl().href,
99
+ url: context.requestUrl.href,
100
100
  method: context.method,
101
101
  headers: parsedHeaders,
102
102
  data: res.response,
@@ -38,11 +38,10 @@ const log = (context, type, message, config, objects) => {
38
38
  if (typeof config.predicate === "function" && !config.predicate()) {
39
39
  return;
40
40
  }
41
- const { computedPath } = context;
42
41
  const color = COLOR_MAP[type];
43
42
  const timestamp = formatTime(new Date());
44
43
  const args = [
45
- `%cnetwork %c[${context.api.name}] ${context.method.toUpperCase()} ${computedPath} %c${message} %c@ ${timestamp}`,
44
+ `%cnetwork %c[${context.api.name}] ${context.method.toUpperCase()} ${context.path} %c${message} %c@ ${timestamp}`,
46
45
  "color:gray",
47
46
  "color:auto",
48
47
  `color:${color}`,
package/package.json CHANGED
@@ -1,79 +1,79 @@
1
- {
2
- "name": "api-def",
3
- "version": "0.8.5",
4
- "description": "Typed API definitions with middleware support",
5
- "main": "cjs/index.js",
6
- "types": "esm/index.d.ts",
7
- "module": "esm/index.js",
8
- "sideEffects": false,
9
- "scripts": {
10
- "prepublishOnly": "npm run test && npm run build",
11
- "test": "npm run test:types && npm run test:lint && npm run test:unit",
12
- "test:unit": "ava",
13
- "test:lint": "npm run lint:strict",
14
- "test:types": "tsc --noEmit -p .",
15
- "example:start": "cd example && npm run start",
16
- "lint": "esw --ext .tsx,.ts src",
17
- "lint:watch": "npm run lint -- --watch",
18
- "lint:fix": "npm run lint -- --fix",
19
- "lint:strict": "npm run lint -- --max-warnings 0",
20
- "cleanup": "rimraf esm && rimraf cjs",
21
- "build": "npm run cleanup && npm run build:esm && npm run build:cjs",
22
- "build:esm": "tsc --module es2015 --target es2016 --outDir esm --preserveWatchOutput",
23
- "build:cjs": "tsc --module commonjs --target es5 --outDir cjs --preserveWatchOutput",
24
- "build:watch": "npm-run-all -p \"build:esm -- -w\" \"build:cjs -- -w\" \"lint:watch\"",
25
- "website:dev": "cd website && npm run start",
26
- "website:deploy": "cd website && npm run deploy"
27
- },
28
- "keywords": [
29
- "typescript",
30
- "javascript",
31
- "node",
32
- "web",
33
- "api",
34
- "typed",
35
- "cache",
36
- "fetch",
37
- "retry",
38
- "middleware"
39
- ],
40
- "author": "James Waterhouse <09jwater@gmail.com>",
41
- "license": "MIT",
42
- "files": [
43
- "LICENSE",
44
- "README.md",
45
- "esm/",
46
- "cjs/"
47
- ],
48
- "repository": "https://github.com/Censkh/api-def",
49
- "ava": {
50
- "extensions": [
51
- "ts"
52
- ],
53
- "files": [
54
- "src/tests/**/*.test.ts"
55
- ],
56
- "nodeArguments": [
57
- "--require=@esbuild-kit/cjs-loader"
58
- ]
59
- },
60
- "devDependencies": {
61
- "@babel/preset-env": "7.14.8",
62
- "@babel/preset-typescript": "7.14.5",
63
- "@esbuild-kit/cjs-loader": "2.4.0",
64
- "@types/axios": "0.14.0",
65
- "@types/node": "16.4.6",
66
- "@types/qs": "6.9.8",
67
- "@typescript-eslint/eslint-plugin": "4.28.5",
68
- "@typescript-eslint/parser": "4.28.5",
69
- "ava": "5.0.1",
70
- "axios": "1.1.3",
71
- "cross-env": "7.0.3",
72
- "eslint": "7.31.0",
73
- "eslint-watch": "7.0.0",
74
- "npm-run-all": "4.1.5",
75
- "qs": "6.11.2",
76
- "typescript": "4.8.4",
77
- "zod": "3.22.4"
78
- }
79
- }
1
+ {
2
+ "name": "api-def",
3
+ "version": "0.9.1",
4
+ "description": "Typed API definitions with middleware support",
5
+ "main": "cjs/index.js",
6
+ "types": "esm/index.d.ts",
7
+ "module": "esm/index.js",
8
+ "sideEffects": false,
9
+ "scripts": {
10
+ "prepublishOnly": "npm run test && npm run build",
11
+ "test": "npm run test:types && npm run test:lint && npm run test:unit",
12
+ "test:unit": "ava",
13
+ "test:lint": "npm run lint:strict",
14
+ "test:types": "tsc --noEmit -p .",
15
+ "example:start": "cd example && npm run start",
16
+ "lint": "esw --ext .tsx,.ts src",
17
+ "lint:watch": "npm run lint -- --watch",
18
+ "lint:fix": "npm run lint -- --fix",
19
+ "lint:strict": "npm run lint -- --max-warnings 0",
20
+ "cleanup": "rimraf esm && rimraf cjs",
21
+ "build": "npm run cleanup && npm run build:esm && npm run build:cjs",
22
+ "build:esm": "tsc --module es2015 --target es2016 --outDir esm --preserveWatchOutput",
23
+ "build:cjs": "tsc --module commonjs --target es5 --outDir cjs --preserveWatchOutput",
24
+ "build:watch": "npm-run-all -p \"build:esm -- -w\" \"build:cjs -- -w\" \"lint:watch\"",
25
+ "website:dev": "cd website && npm run start",
26
+ "website:deploy": "cd website && npm run deploy"
27
+ },
28
+ "keywords": [
29
+ "typescript",
30
+ "javascript",
31
+ "node",
32
+ "web",
33
+ "api",
34
+ "typed",
35
+ "cache",
36
+ "fetch",
37
+ "retry",
38
+ "middleware"
39
+ ],
40
+ "author": "James Waterhouse <09jwater@gmail.com>",
41
+ "license": "MIT",
42
+ "files": [
43
+ "LICENSE",
44
+ "README.md",
45
+ "esm/",
46
+ "cjs/"
47
+ ],
48
+ "repository": "https://github.com/Censkh/api-def",
49
+ "ava": {
50
+ "extensions": [
51
+ "ts"
52
+ ],
53
+ "files": [
54
+ "src/tests/**/*.test.ts"
55
+ ],
56
+ "nodeArguments": [
57
+ "--require=@esbuild-kit/cjs-loader"
58
+ ]
59
+ },
60
+ "devDependencies": {
61
+ "@babel/preset-env": "7.14.8",
62
+ "@babel/preset-typescript": "7.14.5",
63
+ "@esbuild-kit/cjs-loader": "2.4.0",
64
+ "@types/axios": "0.14.0",
65
+ "@types/node": "16.4.6",
66
+ "@types/qs": "6.9.8",
67
+ "@typescript-eslint/eslint-plugin": "4.28.5",
68
+ "@typescript-eslint/parser": "4.28.5",
69
+ "ava": "5.0.1",
70
+ "axios": "1.1.3",
71
+ "cross-env": "7.0.3",
72
+ "eslint": "7.31.0",
73
+ "eslint-watch": "7.0.0",
74
+ "npm-run-all": "4.1.5",
75
+ "qs": "6.11.2",
76
+ "typescript": "4.8.4",
77
+ "zod": "3.22.4"
78
+ }
79
+ }