api-def 0.7.4 → 0.8.0

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 (48) hide show
  1. package/cjs/Api.js +6 -2
  2. package/cjs/ApiTypes.d.ts +30 -10
  3. package/cjs/ApiTypes.js +2 -0
  4. package/cjs/ApiUtils.js +1 -1
  5. package/cjs/Endpoint.d.ts +3 -3
  6. package/cjs/Endpoint.js +13 -8
  7. package/cjs/QueryHandling.d.ts +3 -0
  8. package/cjs/QueryHandling.js +24 -0
  9. package/cjs/RequestConfig.d.ts +2 -0
  10. package/cjs/RequestConfig.js +74 -0
  11. package/cjs/RequestContext.d.ts +4 -4
  12. package/cjs/RequestContext.js +5 -24
  13. package/cjs/RequestError.js +1 -1
  14. package/cjs/Requester.d.ts +1 -1
  15. package/cjs/Requester.js +2 -2
  16. package/cjs/backend/AxiosRequestBackend.js +4 -4
  17. package/cjs/backend/FetchRequestBackend.js +4 -3
  18. package/cjs/backend/MockRequestBackend.js +3 -1
  19. package/esm/Api.js +34 -70
  20. package/esm/ApiConstants.js +5 -5
  21. package/esm/ApiTypes.d.ts +30 -10
  22. package/esm/ApiTypes.js +1 -1
  23. package/esm/ApiUtils.js +12 -13
  24. package/esm/Endpoint.d.ts +3 -3
  25. package/esm/Endpoint.js +42 -74
  26. package/esm/EndpointBuilder.js +14 -16
  27. package/esm/QueryHandling.d.ts +3 -0
  28. package/esm/QueryHandling.js +19 -0
  29. package/esm/RequestConfig.d.ts +2 -0
  30. package/esm/RequestConfig.js +56 -0
  31. package/esm/RequestContext.d.ts +4 -4
  32. package/esm/RequestContext.js +71 -148
  33. package/esm/RequestError.js +7 -7
  34. package/esm/Requester.d.ts +1 -1
  35. package/esm/Requester.js +182 -266
  36. package/esm/TextDecoding.js +20 -20
  37. package/esm/Utils.js +15 -15
  38. package/esm/backend/AxiosRequestBackend.js +34 -67
  39. package/esm/backend/FetchRequestBackend.js +66 -134
  40. package/esm/backend/MockRequestBackend.js +92 -136
  41. package/esm/cache/Caching.js +24 -66
  42. package/esm/cache/LocalForageCacheBackend.js +11 -13
  43. package/esm/cache/LocalStorageCacheBackend.js +19 -62
  44. package/esm/middleware/CacheMiddleware.js +44 -91
  45. package/esm/middleware/LoggingMiddleware.js +36 -39
  46. package/esm/util/retry/index.js +8 -8
  47. package/esm/util/retry/lib/retry.js +11 -22
  48. package/package.json +4 -2
@@ -7,89 +7,56 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- var __generator = (this && this.__generator) || function (thisArg, body) {
11
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
- function verb(n) { return function (v) { return step([n, v]); }; }
14
- function step(op) {
15
- if (f) throw new TypeError("Generator is already executing.");
16
- while (_) try {
17
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
- if (y = 0, t) op = [op[0] & 2, t.value];
19
- switch (op[0]) {
20
- case 0: case 1: t = op; break;
21
- case 4: _.label++; return { value: op[1], done: false };
22
- case 5: _.label++; y = op[1]; op = [0]; continue;
23
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
- default:
25
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
- if (t[2]) _.ops.pop();
30
- _.trys.pop(); continue;
31
- }
32
- op = body.call(thisArg, _);
33
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
- }
36
- };
37
- var axios;
38
- export var isAxiosError = function (error) {
10
+ let axios;
11
+ export const isAxiosError = (error) => {
39
12
  return "isAxiosError" in error;
40
13
  };
41
- var AxiosRequestBackend = /** @class */ (function () {
14
+ export default class AxiosRequestBackend {
42
15
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
43
- function AxiosRequestBackend(axiosLibrary) {
16
+ constructor(axiosLibrary) {
44
17
  this.id = "axios";
45
18
  axios = axiosLibrary;
46
19
  }
47
- AxiosRequestBackend.prototype.extractResponseFromError = function (error) {
48
- return __awaiter(this, void 0, void 0, function () {
49
- return __generator(this, function (_a) {
50
- if (isAxiosError(error)) {
51
- return [2 /*return*/, error.response ? error.response : null];
52
- }
53
- return [2 /*return*/, undefined];
54
- });
20
+ extractResponseFromError(error) {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ if (isAxiosError(error)) {
23
+ return error.response ? error.response : null;
24
+ }
25
+ return undefined;
55
26
  });
56
- };
57
- AxiosRequestBackend.prototype.convertResponse = function (context, response) {
58
- return __awaiter(this, void 0, void 0, function () {
59
- return __generator(this, function (_a) {
60
- return [2 /*return*/, {
61
- data: response.data,
62
- headers: response.headers,
63
- status: response.status,
64
- __lowercaseHeaders: response._lowerCaseResponseHeaders,
65
- }];
66
- });
27
+ }
28
+ convertResponse(context, response) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ return {
31
+ method: context.method,
32
+ url: response.request.res.responseUrl,
33
+ data: response.data,
34
+ headers: response.headers,
35
+ status: response.status,
36
+ __lowercaseHeaders: response._lowerCaseResponseHeaders,
37
+ };
67
38
  });
68
- };
69
- AxiosRequestBackend.prototype.makeRequest = function (context) {
70
- var computedConfig = context.computedConfig;
71
- var canceler = null;
72
- var promise = axios({
39
+ }
40
+ makeRequest(context) {
41
+ const { computedConfig } = context;
42
+ const url = context.getRequestUrl();
43
+ let canceler = null;
44
+ const promise = axios({
73
45
  method: context.method,
74
- baseURL: context.baseUrl,
75
- url: context.computedPath,
46
+ url: url.href,
76
47
  data: context.getParsedBody(),
77
- params: computedConfig.query || {},
78
48
  headers: computedConfig.headers || {},
79
49
  responseType: context.responseType,
80
- cancelToken: new axios.CancelToken(function (cancellerFunc) {
50
+ cancelToken: new axios.CancelToken((cancellerFunc) => {
81
51
  canceler = cancellerFunc;
82
52
  }),
83
- paramsSerializer: context.computedConfig.queryParser,
84
53
  });
85
54
  return {
86
55
  promise: promise,
87
- canceler: function () { return canceler && canceler(); },
56
+ canceler: () => canceler && canceler(),
88
57
  };
89
- };
90
- AxiosRequestBackend.prototype.getErrorInfo = function (error, response) {
58
+ }
59
+ getErrorInfo(error, response) {
91
60
  return undefined;
92
- };
93
- return AxiosRequestBackend;
94
- }());
95
- export default AxiosRequestBackend;
61
+ }
62
+ }
@@ -1,18 +1,3 @@
1
- var __extends = (this && this.__extends) || (function () {
2
- var extendStatics = function (d, b) {
3
- extendStatics = Object.setPrototypeOf ||
4
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
- return extendStatics(d, b);
7
- };
8
- return function (d, b) {
9
- if (typeof b !== "function" && b !== null)
10
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
- extendStatics(d, b);
12
- function __() { this.constructor = d; }
13
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
- };
15
- })();
16
1
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
2
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
3
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -22,149 +7,98 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
22
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
23
8
  });
24
9
  };
25
- var __generator = (this && this.__generator) || function (thisArg, body) {
26
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
27
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
28
- function verb(n) { return function (v) { return step([n, v]); }; }
29
- function step(op) {
30
- if (f) throw new TypeError("Generator is already executing.");
31
- while (_) try {
32
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
33
- if (y = 0, t) op = [op[0] & 2, t.value];
34
- switch (op[0]) {
35
- case 0: case 1: t = op; break;
36
- case 4: _.label++; return { value: op[1], done: false };
37
- case 5: _.label++; y = op[1]; op = [0]; continue;
38
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
39
- default:
40
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
41
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
42
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
43
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
44
- if (t[2]) _.ops.pop();
45
- _.trys.pop(); continue;
46
- }
47
- op = body.call(thisArg, _);
48
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
49
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
50
- }
51
- };
52
10
  import * as Utils from "../Utils";
53
11
  import { getGlobalFetch } from "../Utils";
54
- import { ResponseType } from "../ApiConstants";
55
12
  import { inferResponseType } from "../ApiUtils";
56
- var FetchError = /** @class */ (function (_super) {
57
- __extends(FetchError, _super);
58
- function FetchError() {
59
- return _super !== null && _super.apply(this, arguments) || this;
60
- }
61
- return FetchError;
62
- }(Error));
63
- var FetchRequestBackend = /** @class */ (function () {
64
- function FetchRequestBackend(fetchLibrary) {
13
+ class FetchError extends Error {
14
+ }
15
+ export default class FetchRequestBackend {
16
+ constructor(fetchLibrary) {
65
17
  this.fetch = getGlobalFetch();
66
18
  this.id = "fetch";
67
19
  if (fetchLibrary !== undefined) {
68
20
  this.fetch = fetchLibrary;
69
21
  }
70
22
  }
71
- FetchRequestBackend.prototype.extractResponseFromError = function (error) {
72
- return __awaiter(this, void 0, void 0, function () {
73
- var fetchError;
74
- return __generator(this, function (_a) {
75
- if ("response" in error) {
76
- fetchError = error;
77
- return [2 /*return*/, fetchError.response ? fetchError.response : null];
78
- }
79
- return [2 /*return*/, undefined];
80
- });
23
+ extractResponseFromError(error) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ if ("response" in error) {
26
+ const fetchError = error;
27
+ return fetchError.response ? fetchError.response : null;
28
+ }
29
+ return undefined;
81
30
  });
82
- };
83
- FetchRequestBackend.prototype.convertResponse = function (context, response) {
84
- return __awaiter(this, void 0, void 0, function () {
85
- var contentType, responseType, _a, data, status, headers, error_1, processedHeaders;
86
- return __generator(this, function (_b) {
87
- switch (_b.label) {
88
- case 0:
89
- contentType = response.headers.get("Content-Type");
90
- responseType = inferResponseType(contentType);
91
- if (!!response.__text) return [3 /*break*/, 2];
92
- _a = response;
93
- return [4 /*yield*/, response.clone().text()];
94
- case 1:
95
- _a.__text = _b.sent();
96
- _b.label = 2;
97
- case 2:
98
- data = response.__text;
99
- status = response.status, headers = response.headers;
100
- _b.label = 3;
101
- case 3:
102
- _b.trys.push([3, 7, , 8]);
103
- if (!(responseType === ResponseType.ArrayBuffer)) return [3 /*break*/, 5];
104
- return [4 /*yield*/, response.clone().arrayBuffer()];
105
- case 4:
106
- data = _b.sent();
107
- return [3 /*break*/, 6];
108
- case 5:
109
- if (responseType === ResponseType.Json) {
110
- data = JSON.parse(response.__text);
111
- }
112
- _b.label = 6;
113
- case 6: return [3 /*break*/, 8];
114
- case 7:
115
- error_1 = _b.sent();
116
- throw Object.assign(new Error("[api-def] Invalid '".concat(context.responseType, "' response, got: '").concat(response.__text, "'")), {
117
- response: response,
118
- });
119
- case 8:
120
- processedHeaders = {};
121
- headers.forEach(function (value, key) {
122
- processedHeaders[key] = value;
123
- });
124
- return [2 /*return*/, {
125
- __lowercaseHeaders: processedHeaders,
126
- data: data,
127
- status: status,
128
- headers: processedHeaders,
129
- }];
31
+ }
32
+ convertResponse(context, response) {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ const contentType = response.headers.get("Content-Type");
35
+ const responseType = inferResponseType(contentType);
36
+ if (!response.__text) {
37
+ response.__text = yield response.clone().text();
38
+ }
39
+ let data = response.__text;
40
+ const { status, headers } = response;
41
+ try {
42
+ if (responseType === "arraybuffer") {
43
+ data = yield response.clone().arrayBuffer();
44
+ }
45
+ else if (responseType === "json") {
46
+ data = JSON.parse(response.__text);
130
47
  }
48
+ }
49
+ catch (error) {
50
+ throw Object.assign(new Error(`[api-def] Invalid '${context.responseType}' response, got: '${response.__text}'`), {
51
+ response,
52
+ });
53
+ }
54
+ const processedHeaders = {};
55
+ headers.forEach((value, key) => {
56
+ processedHeaders[key] = value;
131
57
  });
58
+ return {
59
+ __lowercaseHeaders: processedHeaders,
60
+ method: context.method,
61
+ url: response.url,
62
+ data: data,
63
+ status: status,
64
+ headers: processedHeaders,
65
+ };
132
66
  });
133
- };
134
- FetchRequestBackend.prototype.makeRequest = function (context) {
67
+ }
68
+ makeRequest(context) {
135
69
  if (!this.fetch) {
136
70
  throw new Error("[api-def] No fetch impl was provided to FetchRequestBackend");
137
71
  }
138
- var computedConfig = context.computedConfig;
72
+ const { computedConfig } = context;
139
73
  // abort controller is a newer feature than fetch
140
- var abortController = AbortController && new AbortController();
141
- var abortSignal = abortController ? abortController.signal : undefined;
142
- var softAbort = false;
143
- var responded = false;
144
- var body = context.getParsedBody();
145
- var bodyJsonify = body !== null && typeof body === "object";
146
- var headers = Utils.assign({
74
+ const abortController = AbortController && new AbortController();
75
+ const abortSignal = abortController ? abortController.signal : undefined;
76
+ let softAbort = false;
77
+ let responded = false;
78
+ const body = context.getParsedBody();
79
+ const bodyJsonify = body !== null && typeof body === "object";
80
+ const headers = Utils.assign({
147
81
  // logic from axios
148
82
  "Content-Type": bodyJsonify ? "application/json;charset=utf-8" : "application/x-www-form-urlencoded",
149
83
  }, computedConfig.headers);
150
- var parsedHeaders = Object.keys(headers).reduce(function (parsedHeaders, key) {
151
- var value = headers[key];
84
+ const parsedHeaders = Object.keys(headers).reduce((parsedHeaders, key) => {
85
+ const value = headers[key];
152
86
  if (value !== undefined) {
153
87
  parsedHeaders[key] = value;
154
88
  }
155
89
  return parsedHeaders;
156
90
  }, {});
157
- var url = context.getRequestUrl();
158
- var promise = this.fetch(url.href, {
91
+ const url = context.getRequestUrl();
92
+ const promise = this.fetch(url.href, {
159
93
  method: context.method,
160
94
  body: bodyJsonify ? JSON.stringify(body) : body,
161
95
  headers: parsedHeaders,
162
96
  mode: "cors",
163
97
  signal: abortSignal,
164
- }).then(function (response) {
98
+ }).then((response) => {
165
99
  responded = true;
166
100
  if (!response.ok) {
167
- var error = new FetchError("Fetch failed");
101
+ const error = new FetchError("Fetch failed");
168
102
  error.response = response;
169
103
  throw error;
170
104
  }
@@ -176,15 +110,13 @@ var FetchRequestBackend = /** @class */ (function () {
176
110
  return {
177
111
  promise: promise,
178
112
  canceler: abortSignal
179
- ? function () { return !responded && abortController.abort(); }
180
- : function () {
113
+ ? () => !responded && abortController.abort()
114
+ : () => {
181
115
  softAbort = true;
182
116
  },
183
117
  };
184
- };
185
- FetchRequestBackend.prototype.getErrorInfo = function (error, response) {
118
+ }
119
+ getErrorInfo(error, response) {
186
120
  return undefined;
187
- };
188
- return FetchRequestBackend;
189
- }());
190
- export default FetchRequestBackend;
121
+ }
122
+ }
@@ -7,154 +7,110 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- var __generator = (this && this.__generator) || function (thisArg, body) {
11
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
- function verb(n) { return function (v) { return step([n, v]); }; }
14
- function step(op) {
15
- if (f) throw new TypeError("Generator is already executing.");
16
- while (_) try {
17
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
- if (y = 0, t) op = [op[0] & 2, t.value];
19
- switch (op[0]) {
20
- case 0: case 1: t = op; break;
21
- case 4: _.label++; return { value: op[1], done: false };
22
- case 5: _.label++; y = op[1]; op = [0]; continue;
23
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
- default:
25
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
- if (t[2]) _.ops.pop();
30
- _.trys.pop(); continue;
31
- }
32
- op = body.call(thisArg, _);
33
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
- }
36
- };
37
10
  import * as Utils from "../Utils";
38
11
  import { delayThenReturn, randInt } from "../Utils";
39
12
  import { convertToRequestError, RequestErrorCode } from "../RequestError";
40
- var MockRequestBackend = /** @class */ (function () {
41
- function MockRequestBackend() {
13
+ export default class MockRequestBackend {
14
+ constructor() {
42
15
  this.id = "mock";
43
16
  }
44
- MockRequestBackend.prototype.convertResponse = function (context, response, error) {
45
- return __awaiter(this, void 0, void 0, function () {
46
- return __generator(this, function (_a) {
47
- return [2 /*return*/, response];
48
- });
17
+ convertResponse(context, response, error) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ return response;
49
20
  });
50
- };
51
- MockRequestBackend.prototype.extractResponseFromError = function (error) {
52
- return __awaiter(this, void 0, void 0, function () {
53
- var fetchError;
54
- return __generator(this, function (_a) {
55
- if ("response" in error) {
56
- fetchError = error;
57
- return [2 /*return*/, fetchError.response ? fetchError.response : null];
58
- }
59
- return [2 /*return*/, undefined];
60
- });
21
+ }
22
+ extractResponseFromError(error) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ if ("response" in error) {
25
+ const fetchError = error;
26
+ return fetchError.response ? fetchError.response : null;
27
+ }
28
+ return undefined;
61
29
  });
62
- };
63
- MockRequestBackend.prototype.runRequest = function (context) {
30
+ }
31
+ runRequest(context) {
64
32
  var _a, _b, _c, _d;
65
- return __awaiter(this, void 0, void 0, function () {
66
- var mockingFunc, req, res, delay, delayMs, min, max, _e, parsedHeaders;
67
- return __generator(this, function (_f) {
68
- switch (_f.label) {
69
- case 0:
70
- mockingFunc = (_a = context.mocking) === null || _a === void 0 ? void 0 : _a.handler;
71
- if (!mockingFunc) {
72
- throw convertToRequestError({
73
- error: new Error("[api-def] Attempted to run mocked request without mocking function"),
74
- code: RequestErrorCode.REQUEST_INVALID_CONFIG,
75
- context: context,
76
- });
77
- }
78
- req = {
79
- body: context.getParsedBody(),
80
- params: (_b = context.computedConfig.params) !== null && _b !== void 0 ? _b : {},
81
- query: context.computedConfig.query,
82
- headers: (_c = context.computedConfig.headers) !== null && _c !== void 0 ? _c : {},
83
- url: context.getRequestUrl().toString(),
84
- };
85
- res = {
86
- statusCode: -1,
87
- headers: {},
88
- response: undefined,
89
- status: function (statusCode) {
90
- res.statusCode = statusCode;
91
- return res;
92
- },
93
- send: function (response) {
94
- res.response = response;
95
- if (response && typeof response === "object") {
96
- res.headers["Content-Type"] = "application/json";
97
- }
98
- return res;
99
- },
100
- };
101
- if (!((_d = context.mocking) === null || _d === void 0 ? void 0 : _d.delay)) return [3 /*break*/, 3];
102
- delay = context.mocking.delay;
103
- delayMs = void 0;
104
- if (typeof delay === "number") {
105
- delayMs = delay;
106
- }
107
- else {
108
- min = delay[0], max = delay[1];
109
- if (min > max) {
110
- throw convertToRequestError({
111
- error: new Error("[api-def] Min delay cannot be greater than max delay"),
112
- code: RequestErrorCode.REQUEST_INVALID_CONFIG,
113
- context: context,
114
- });
115
- }
116
- delayMs = randInt(min, max);
117
- }
118
- _e = delayThenReturn;
119
- return [4 /*yield*/, mockingFunc(req, res)];
120
- case 1: return [4 /*yield*/, _e.apply(void 0, [_f.sent(), delayMs])];
121
- case 2:
122
- _f.sent();
123
- return [3 /*break*/, 5];
124
- case 3: return [4 /*yield*/, mockingFunc(req, res)];
125
- case 4:
126
- _f.sent();
127
- _f.label = 5;
128
- case 5:
129
- if (res.response === undefined) {
130
- throw convertToRequestError({
131
- error: new Error("[api-def] Mocked API did not respond"),
132
- code: RequestErrorCode.REQUEST_INVALID_CONFIG,
133
- context: context,
134
- });
135
- }
136
- parsedHeaders = Object.keys(res.headers).reduce(function (parsedHeaders, key) {
137
- parsedHeaders[key] = res.headers[key].toString();
138
- return parsedHeaders;
139
- }, {});
140
- return [2 /*return*/, {
141
- headers: parsedHeaders,
142
- data: res.response,
143
- status: res.statusCode,
144
- }];
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ const mockingFunc = (_a = context.mocking) === null || _a === void 0 ? void 0 : _a.handler;
35
+ if (!mockingFunc) {
36
+ throw convertToRequestError({
37
+ error: new Error("[api-def] Attempted to run mocked request without mocking function"),
38
+ code: RequestErrorCode.REQUEST_INVALID_CONFIG,
39
+ context,
40
+ });
41
+ }
42
+ const req = {
43
+ body: context.getParsedBody(),
44
+ params: (_b = context.computedConfig.params) !== null && _b !== void 0 ? _b : {},
45
+ query: context.computedConfig.queryObject,
46
+ headers: (_c = context.computedConfig.headers) !== null && _c !== void 0 ? _c : {},
47
+ url: context.getRequestUrl().toString(),
48
+ };
49
+ const res = {
50
+ statusCode: -1,
51
+ headers: {},
52
+ response: undefined,
53
+ status(statusCode) {
54
+ res.statusCode = statusCode;
55
+ return res;
56
+ },
57
+ send(response) {
58
+ res.response = response;
59
+ if (response && typeof response === "object") {
60
+ res.headers["Content-Type"] = "application/json";
61
+ }
62
+ return res;
63
+ },
64
+ };
65
+ if ((_d = context.mocking) === null || _d === void 0 ? void 0 : _d.delay) {
66
+ const delay = context.mocking.delay;
67
+ let delayMs;
68
+ if (typeof delay === "number") {
69
+ delayMs = delay;
145
70
  }
146
- });
71
+ else {
72
+ const [min, max] = delay;
73
+ if (min > max) {
74
+ throw convertToRequestError({
75
+ error: new Error("[api-def] Min delay cannot be greater than max delay"),
76
+ code: RequestErrorCode.REQUEST_INVALID_CONFIG,
77
+ context,
78
+ });
79
+ }
80
+ delayMs = randInt(min, max);
81
+ }
82
+ yield delayThenReturn(yield mockingFunc(req, res), delayMs);
83
+ }
84
+ else {
85
+ yield mockingFunc(req, res);
86
+ }
87
+ if (res.response === undefined) {
88
+ throw convertToRequestError({
89
+ error: new Error("[api-def] Mocked API did not respond"),
90
+ code: RequestErrorCode.REQUEST_INVALID_CONFIG,
91
+ context,
92
+ });
93
+ }
94
+ const parsedHeaders = Object.keys(res.headers).reduce((parsedHeaders, key) => {
95
+ parsedHeaders[key] = res.headers[key].toString();
96
+ return parsedHeaders;
97
+ }, {});
98
+ return {
99
+ url: context.getRequestUrl().href,
100
+ method: context.method,
101
+ headers: parsedHeaders,
102
+ data: res.response,
103
+ status: res.statusCode,
104
+ };
147
105
  });
148
- };
149
- MockRequestBackend.prototype.makeRequest = function (context) {
106
+ }
107
+ makeRequest(context) {
150
108
  return {
151
109
  canceler: Utils.noop,
152
110
  promise: this.runRequest(context),
153
111
  };
154
- };
155
- MockRequestBackend.prototype.getErrorInfo = function (error, response) {
112
+ }
113
+ getErrorInfo(error, response) {
156
114
  return undefined;
157
- };
158
- return MockRequestBackend;
159
- }());
160
- export default MockRequestBackend;
115
+ }
116
+ }