@zcatalyst/transport 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENCE +55 -1
  2. package/README.md +266 -0
  3. package/dist-cjs/fetch-handler.js +269 -0
  4. package/dist-cjs/http-handler.js +404 -0
  5. package/dist-cjs/index.browser.js +23 -0
  6. package/dist-cjs/index.js +34 -0
  7. package/dist-cjs/utils/clonable-stream.js +107 -0
  8. package/dist-cjs/utils/constants.js +55 -0
  9. package/dist-cjs/utils/enums.js +22 -0
  10. package/dist-cjs/utils/errors.js +10 -0
  11. package/dist-cjs/utils/form-data.js +223 -0
  12. package/dist-cjs/utils/helpers.js +10 -0
  13. package/dist-cjs/utils/interfaces.js +2 -0
  14. package/dist-cjs/utils/request-agent.js +22 -0
  15. package/dist-cjs/utils/request-timeout.js +14 -0
  16. package/dist-es/fetch-handler.js +261 -0
  17. package/dist-es/http-handler.js +362 -0
  18. package/dist-es/index.browser.js +13 -0
  19. package/dist-es/index.js +21 -0
  20. package/dist-es/utils/clonable-stream.js +104 -0
  21. package/dist-es/utils/constants.js +52 -0
  22. package/dist-es/utils/enums.js +19 -0
  23. package/dist-es/utils/errors.js +6 -0
  24. package/dist-es/utils/form-data.js +218 -0
  25. package/dist-es/utils/helpers.js +7 -0
  26. package/dist-es/utils/interfaces.js +1 -0
  27. package/dist-es/utils/request-agent.js +19 -0
  28. package/dist-es/utils/request-timeout.js +11 -0
  29. package/dist-types/fetch-handler.d.ts +149 -0
  30. package/dist-types/http-handler.d.ts +79 -0
  31. package/dist-types/index.browser.d.ts +29 -0
  32. package/dist-types/index.d.ts +36 -0
  33. package/dist-types/ts3.4/fetch-handler.d.ts +149 -0
  34. package/dist-types/ts3.4/http-handler.d.ts +79 -0
  35. package/dist-types/ts3.4/index.browser.d.ts +29 -0
  36. package/dist-types/ts3.4/index.d.ts +36 -0
  37. package/dist-types/ts3.4/utils/clonable-stream.d.ts +75 -0
  38. package/dist-types/ts3.4/utils/constants.d.ts +11 -0
  39. package/dist-types/ts3.4/utils/enums.d.ts +16 -0
  40. package/dist-types/ts3.4/utils/errors.d.ts +11 -0
  41. package/dist-types/ts3.4/utils/form-data.d.ts +285 -0
  42. package/dist-types/ts3.4/utils/helpers.d.ts +13 -0
  43. package/dist-types/ts3.4/utils/interfaces.d.ts +68 -0
  44. package/dist-types/ts3.4/utils/request-agent.d.ts +12 -0
  45. package/dist-types/ts3.4/utils/request-timeout.d.ts +13 -0
  46. package/dist-types/utils/clonable-stream.d.ts +75 -0
  47. package/dist-types/utils/constants.d.ts +11 -0
  48. package/dist-types/utils/enums.d.ts +16 -0
  49. package/dist-types/utils/errors.d.ts +11 -0
  50. package/dist-types/utils/form-data.d.ts +285 -0
  51. package/dist-types/utils/helpers.d.ts +13 -0
  52. package/dist-types/utils/interfaces.d.ts +68 -0
  53. package/dist-types/utils/request-agent.d.ts +12 -0
  54. package/dist-types/utils/request-timeout.d.ts +13 -0
  55. package/package.json +37 -7
@@ -0,0 +1,362 @@
1
+ import { addDefaultAppHeaders } from '@zcatalyst/auth-admin';
2
+ import { CONSTANTS, getServicePath, LOGGER } from '@zcatalyst/utils';
3
+ import http from 'http';
4
+ import https from 'https';
5
+ import { ReadableStream } from 'node:stream/web';
6
+ import { stringify } from 'querystring';
7
+ import { Readable } from 'stream';
8
+ import { URL } from 'url';
9
+ import { inspect } from 'util';
10
+ import pkg from '../package.json';
11
+ const { version } = pkg;
12
+ import { CatalystAPIError } from './utils/errors';
13
+ import FORM from './utils/form-data';
14
+ import { isHttps } from './utils/helpers';
15
+ import RequestAgent from './utils/request-agent';
16
+ const { IS_LOCAL, USER_KEY_NAME, CREDENTIAL_USER, CATALYST_ORIGIN, USER_AGENT, APM_INSIGHT, ACCEPT_HEADER, REQ_RETRY_THRESHOLD, IS_APM } = CONSTANTS;
17
+ export class DefaultHttpResponse {
18
+ constructor(resp) {
19
+ this.statusCode = resp.statusCode;
20
+ this.headers = resp.headers;
21
+ this.config = resp.config;
22
+ this.resp = resp;
23
+ }
24
+ get data() {
25
+ switch (this.config.expecting) {
26
+ case "string":
27
+ if (this.resp.data === undefined) {
28
+ throw new CatalystAPIError('UNPARSABLE_RESPONSE', `Error while processing response data. Raw server ` +
29
+ `response: "${this.resp.data}". Status code: "${this.statusCode}".`, '', this.statusCode);
30
+ }
31
+ return this.resp.data;
32
+ case "buffer":
33
+ if (this.resp.buffer === undefined) {
34
+ throw new CatalystAPIError('UNPARSABLE_RESPONSE', `Error while processing response buffer. Raw server ` +
35
+ `response: "${this.resp.data}". Status code: "${this.statusCode}".`, '', this.statusCode);
36
+ }
37
+ return this.resp.buffer;
38
+ case "raw":
39
+ return this.resp.stream;
40
+ default:
41
+ try {
42
+ return JSON.parse(this.resp.data);
43
+ }
44
+ catch (e) {
45
+ throw new CatalystAPIError('UNPARSABLE_RESPONSE', `Error while parsing response data: "${inspect(e)}". Raw server ` +
46
+ `response: "${this.resp.data}". Status code: "${this.statusCode}".`, '', this.statusCode);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ function rejectWithContext(reject, statusCode, data) {
52
+ try {
53
+ const catalystError = JSON.parse(data);
54
+ reject({
55
+ statusCode,
56
+ code: catalystError.data.error_code,
57
+ message: catalystError.data.message
58
+ });
59
+ return;
60
+ }
61
+ catch {
62
+ reject({
63
+ statusCode,
64
+ message: inspect(data)
65
+ });
66
+ }
67
+ }
68
+ async function streamToBuffer(stream) {
69
+ const chunks = [];
70
+ return new Promise((resolve, reject) => {
71
+ stream.destroyed && reject('Invalid response stream');
72
+ stream.on('data', (chunk) => {
73
+ chunks.push(chunk);
74
+ });
75
+ stream.on('error', reject);
76
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
77
+ });
78
+ }
79
+ function constructFormData(data) {
80
+ const formData = new FORM();
81
+ const keyData = Object.keys(data);
82
+ keyData.forEach((key) => {
83
+ formData.append(key, data[key]);
84
+ });
85
+ return formData;
86
+ }
87
+ async function _finalizeRequest(resolve, reject, response) {
88
+ if (response.statusCode === undefined) {
89
+ reject(new CatalystAPIError('UNKNOWN_STATUSCODE', 'unable to obtain status code from response', response));
90
+ return;
91
+ }
92
+ if (response.statusCode >= 200 && response.statusCode < 300) {
93
+ resolve(response);
94
+ return;
95
+ }
96
+ if (response.stream?.pipe === undefined) {
97
+ rejectWithContext(reject, response.statusCode, response.data);
98
+ return;
99
+ }
100
+ try {
101
+ if (response.stream !== undefined && response.data === undefined) {
102
+ const responseBuffer = await streamToBuffer(response.stream);
103
+ response.data = responseBuffer.toString();
104
+ }
105
+ if (response.statusCode === 404) {
106
+ rejectWithContext(reject, response.statusCode, response.data || 'Not Found');
107
+ }
108
+ else if (response.statusCode === 403) {
109
+ rejectWithContext(reject, response.statusCode, response.data || 'Access Denied');
110
+ }
111
+ else if (response.statusCode === 401) {
112
+ rejectWithContext(reject, response.statusCode, response.data || 'Unauthorized');
113
+ }
114
+ else {
115
+ rejectWithContext(reject, response.statusCode, response.data || 'Unknown response');
116
+ }
117
+ }
118
+ catch (e) {
119
+ const errMsg = e instanceof Error ? e.message : inspect(e);
120
+ rejectWithContext(reject, response.statusCode, errMsg);
121
+ }
122
+ }
123
+ function _appendQueryData(url, data) {
124
+ if (data && Object.keys(data).length > 0) {
125
+ url += url.includes('?') ? '&' : '?';
126
+ url += stringify(data);
127
+ }
128
+ return url;
129
+ }
130
+ async function _request(transport, options, config, data, retryCount = 0) {
131
+ const clonedData = data === undefined
132
+ ? undefined
133
+ : config.type !== "file"
134
+ ?
135
+ data
136
+ :
137
+ data.createClone();
138
+ return new Promise(async (resolve, reject) => {
139
+ const retryRequest = async (err) => {
140
+ LOGGER.warn('>>> RETRYING REQUEST ');
141
+ if (retryCount++ === REQ_RETRY_THRESHOLD) {
142
+ reject(err);
143
+ return;
144
+ }
145
+ try {
146
+ options.agent = new RequestAgent(isHttps(config.url), options.hostname, true).agent;
147
+ const resp = await _request(transport, options, config, clonedData, retryCount);
148
+ resolve(resp);
149
+ }
150
+ catch (e) {
151
+ reject(e);
152
+ }
153
+ };
154
+ const startTimeStamp = Date.now();
155
+ const req = transport.request(options, async (res) => {
156
+ if (req.destroyed) {
157
+ return;
158
+ }
159
+ const response = {
160
+ headers: res.headers,
161
+ request: req,
162
+ stream: res,
163
+ statusCode: res.statusCode,
164
+ config
165
+ };
166
+ LOGGER.debug(`>>> HTTP REQUEST : ${req.method?.toUpperCase()} ${req.protocol}//${req.host}${req.path}`);
167
+ process.env.ZC_SECURE?.toLowerCase() === 'override' &&
168
+ LOGGER.fine(`>>> REQUEST HEADERS : ${JSON.stringify(options.headers)}`);
169
+ LOGGER.debug(`<<< HTTP RESPONSE : ${res.statusCode} : ${Date.now() - startTimeStamp} ms`);
170
+ process.env.ZC_SECURE?.toLowerCase() === 'override' &&
171
+ LOGGER.fine(`<<< RESPONSE HEADERS : ${JSON.stringify(res.headers)}`);
172
+ if (config.expecting === "raw") {
173
+ return _finalizeRequest(resolve, reject, response);
174
+ }
175
+ try {
176
+ const responseBuffer = await streamToBuffer(res);
177
+ response.data = responseBuffer.toString();
178
+ response.buffer = responseBuffer;
179
+ }
180
+ catch (err) {
181
+ if (req.destroyed || (config.abortSignal && config.abortSignal.aborted)) {
182
+ req.destroy();
183
+ return;
184
+ }
185
+ reject(err);
186
+ }
187
+ _finalizeRequest(resolve, reject, response);
188
+ });
189
+ req.on('error', (err) => {
190
+ LOGGER.debug(`>>> HTTP REQUEST : ${req.method?.toUpperCase()} ${req.protocol}//${req.host}${req.path}`);
191
+ process.env.ZC_SECURE?.toLowerCase() === 'override' &&
192
+ LOGGER.fine(`>>> REQUEST HEADERS : ${JSON.stringify(options.headers)}`);
193
+ LOGGER.debug(`<<< HTTP REQUEST ERROR : ${inspect(err)} : ${Date.now() - startTimeStamp} ms`);
194
+ if (req.destroyed || config.type === "raw") {
195
+ return reject(err);
196
+ }
197
+ retryRequest(err);
198
+ });
199
+ if (data === undefined) {
200
+ req.end();
201
+ return;
202
+ }
203
+ if (config.type !== "file" && config.type !== "raw") {
204
+ req.write(data);
205
+ req.end();
206
+ return;
207
+ }
208
+ if (data instanceof ReadableStream) {
209
+ data = webStreamToNodeStream(data);
210
+ }
211
+ if (typeof data === 'string' || Buffer.isBuffer(data)) {
212
+ req.write(data);
213
+ req.end();
214
+ return;
215
+ }
216
+ data.on('error', (er) => {
217
+ reject(er);
218
+ req.end();
219
+ });
220
+ data.pipe(req).on('finish', req.end);
221
+ });
222
+ }
223
+ function webStreamToNodeStream(webStream) {
224
+ const reader = webStream.getReader();
225
+ return new Readable({
226
+ async read() {
227
+ const { done, value } = await reader.read();
228
+ if (done) {
229
+ this.push(null);
230
+ }
231
+ else {
232
+ this.push(value);
233
+ }
234
+ }
235
+ });
236
+ }
237
+ async function sendRequest(config, componentName, componentVersion) {
238
+ let data;
239
+ let userAgent = USER_AGENT.PREFIX + version;
240
+ if (componentName) {
241
+ userAgent += ` ${componentName}/${componentVersion || 'unknown'}`;
242
+ }
243
+ let headers = Object.assign({
244
+ [USER_AGENT.KEY]: userAgent
245
+ }, config.headers);
246
+ if (config.data !== undefined) {
247
+ switch (config.type) {
248
+ case "json":
249
+ data = JSON.stringify(config.data);
250
+ headers['Content-Type'] = 'application/json';
251
+ break;
252
+ case "file":
253
+ data = constructFormData(config.data);
254
+ headers = data.getHeaders(headers);
255
+ break;
256
+ case "raw":
257
+ data = config.data;
258
+ if (headers['Content-Type'] === undefined) {
259
+ headers['Content-Type'] = 'application/octet-stream';
260
+ }
261
+ break;
262
+ default:
263
+ data = stringify(config.data);
264
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
265
+ headers['Content-Length'] = Buffer.byteLength(data) + '';
266
+ }
267
+ }
268
+ const origin = config.origin || CATALYST_ORIGIN;
269
+ config.url = config.url || new URL(config.path || '', origin).href;
270
+ if (config.qs !== undefined) {
271
+ config.url = _appendQueryData(config.url, config.qs);
272
+ }
273
+ const parsedUrl = new URL(config.url);
274
+ if (parsedUrl.hostname === null) {
275
+ throw new CatalystAPIError('UNPARSABLE_CONFIG', 'Hostname cannot be null', config.path, 400);
276
+ }
277
+ const isHttpsProtocol = isHttps(parsedUrl);
278
+ const requestAgent = new RequestAgent(isHttpsProtocol, parsedUrl.hostname, false);
279
+ parsedUrl.searchParams?.sort();
280
+ const options = {
281
+ hostname: parsedUrl.hostname,
282
+ port: parsedUrl.port,
283
+ path: parsedUrl.pathname + parsedUrl.search,
284
+ method: config.method,
285
+ headers,
286
+ agent: requestAgent.agent
287
+ };
288
+ const transport = isHttpsProtocol ? https : http;
289
+ return _request(transport, options, config, data);
290
+ }
291
+ export class HttpClient {
292
+ constructor(app) {
293
+ this.app = app;
294
+ }
295
+ async send(req, apmTrackerName, componentVersion) {
296
+ req.headers = Object.assign({}, req.headers);
297
+ req.qs = Object.assign({}, req.qs);
298
+ req.retry = req.retry || true;
299
+ if (this.app !== undefined && req.service !== "external") {
300
+ const user = this.app.credential.getCurrentUser();
301
+ req.headers = addDefaultAppHeaders(req.headers, this.app.config);
302
+ req.headers[USER_KEY_NAME] = this.app.credential.getCurrentUserType();
303
+ if (IS_LOCAL === 'true') {
304
+ switch (user) {
305
+ case CREDENTIAL_USER.admin:
306
+ req.origin =
307
+ 'https://' +
308
+ CATALYST_ORIGIN.replace('https://', '').replace('http://', '');
309
+ break;
310
+ case CREDENTIAL_USER.user:
311
+ req.origin = 'https://' + this.app.config.projectDomain;
312
+ break;
313
+ }
314
+ }
315
+ if (req.service === "baas") {
316
+ req.headers[ACCEPT_HEADER.KEY] =
317
+ ACCEPT_HEADER.VALUE + ', ' + (req.headers[ACCEPT_HEADER.KEY] || '');
318
+ }
319
+ req.path =
320
+ getServicePath(req.service) + `/project/${this.app.config.projectId}` + req.path;
321
+ }
322
+ try {
323
+ let resp;
324
+ if (req.track && apmTrackerName && IS_APM === 'true') {
325
+ try {
326
+ const apminsight = await import('apminsight');
327
+ resp = await apminsight.startTracker(APM_INSIGHT.tracker_name, apmTrackerName, () => sendRequest(req, apmTrackerName, componentVersion));
328
+ }
329
+ catch (err) {
330
+ throw new CatalystAPIError('APM_TRACKER_ERROR', 'To enable APM tracking locally, please download the apminsight package from the UI and place it in the node_modules directory of your project.', err, 400);
331
+ }
332
+ }
333
+ else {
334
+ resp = await sendRequest(req, apmTrackerName, componentVersion);
335
+ }
336
+ return new DefaultHttpResponse(resp);
337
+ }
338
+ catch (err) {
339
+ if (err instanceof Error) {
340
+ throw new CatalystAPIError('REQUEST_FAILURE', err.message, err, err.message.includes('ECONNREFUSED') ? 503 : 400);
341
+ }
342
+ throw err;
343
+ }
344
+ }
345
+ }
346
+ export class AuthorizedHttpClient extends HttpClient {
347
+ constructor(app, component) {
348
+ super(app);
349
+ if (component) {
350
+ this.componentName = component.getComponentName();
351
+ this.componentVersion = component.getComponentVersion?.();
352
+ }
353
+ }
354
+ async send(request) {
355
+ const requestCopy = Object.assign({ user: CREDENTIAL_USER.user }, request);
356
+ requestCopy.headers = Object.assign({}, request.headers);
357
+ if (request.auth !== false) {
358
+ await this.app?.authenticateRequest(requestCopy);
359
+ }
360
+ return await super.send(requestCopy, this.componentName, this.componentVersion);
361
+ }
362
+ }
@@ -0,0 +1,13 @@
1
+ import { ResponseHandler } from './fetch-handler';
2
+ export { CatalystService, CONSTANTS } from '@zcatalyst/utils';
3
+ export { PrefixedCatalystError } from '@zcatalyst/utils';
4
+ export class Handler {
5
+ constructor(app, component) {
6
+ this.component = component;
7
+ }
8
+ async send(options) {
9
+ return (await ResponseHandler.send(options, this.component?.getComponentName(), this.component?.getComponentVersion?.()));
10
+ }
11
+ }
12
+ export { RequestType, ResponseType } from './utils/enums';
13
+ export { CatalystAPIError } from './utils/errors';
@@ -0,0 +1,21 @@
1
+ import { ZCAuth } from '@zcatalyst/auth-admin';
2
+ import { AuthorizedHttpClient } from './http-handler';
3
+ import FormData from './utils/form-data';
4
+ export { CatalystService, CONSTANTS } from '@zcatalyst/utils';
5
+ export { PrefixedCatalystError } from '@zcatalyst/utils';
6
+ export class Handler {
7
+ constructor(app, component) {
8
+ if (!app) {
9
+ app = new ZCAuth().getDefaultCredentials();
10
+ }
11
+ this.app = app;
12
+ this.component = component;
13
+ }
14
+ async send(options) {
15
+ const _httpRequester = new AuthorizedHttpClient(this.app, this.component);
16
+ return (await _httpRequester.send(options));
17
+ }
18
+ }
19
+ export { RequestType, ResponseType } from './utils/enums';
20
+ export { CatalystAPIError } from './utils/errors';
21
+ export { FormData };
@@ -0,0 +1,104 @@
1
+ import { nextTick } from 'process';
2
+ import { PassThrough } from 'stream';
3
+ function clonePiped(that) {
4
+ if (--that._clonesCount === 0 && !that.destroyed) {
5
+ that._original?.pipe(that);
6
+ that._original = undefined;
7
+ }
8
+ }
9
+ function _destroy(error, callback) {
10
+ if (!error) {
11
+ this.push(null);
12
+ this.end();
13
+ }
14
+ nextTick(callback, error);
15
+ }
16
+ function forwardDestroy(src, dest) {
17
+ function destroy(err) {
18
+ src.removeListener('close', onClose);
19
+ dest.destroy(err);
20
+ }
21
+ function onClose() {
22
+ dest.end();
23
+ }
24
+ src.on('error', destroy);
25
+ src.on('close', onClose);
26
+ }
27
+ class StreamClone extends PassThrough {
28
+ constructor(parent) {
29
+ super({ objectMode: parent.readableObjectMode });
30
+ this.parent = parent;
31
+ forwardDestroy(parent, this);
32
+ parent._internalPipe = true;
33
+ parent.pipe(this);
34
+ parent._internalPipe = false;
35
+ this.on('newListener', this.onDataClone);
36
+ this.once('resume', this.onResumeClone);
37
+ }
38
+ onDataClone(event, _listener) {
39
+ if (event === 'data' || event === 'readable' || event === 'close') {
40
+ nextTick(clonePiped, this.parent);
41
+ this.removeListener('newListener', this.onDataClone);
42
+ this.removeListener('resume', this.onResumeClone);
43
+ }
44
+ }
45
+ onResumeClone() {
46
+ this.removeListener('newListener', this.onDataClone);
47
+ this.removeListener('resume', this.onResumeClone);
48
+ nextTick(clonePiped, this.parent);
49
+ }
50
+ clone() {
51
+ return this.parent.clone();
52
+ }
53
+ isCloneable(stream) {
54
+ return stream instanceof CloneableStream || stream instanceof StreamClone;
55
+ }
56
+ }
57
+ export default class CloneableStream extends PassThrough {
58
+ constructor(stream) {
59
+ super({ objectMode: stream.readableObjectMode });
60
+ this._original = stream;
61
+ this._clonesCount = 1;
62
+ this._internalPipe = false;
63
+ forwardDestroy(stream, this);
64
+ this.on('newListener', this.onData);
65
+ this.on('resume', this.onResume);
66
+ this._hasListener = true;
67
+ this._destroy = _destroy;
68
+ }
69
+ onData(event, _listener) {
70
+ if (event === 'data' || event === 'readable') {
71
+ this._hasListener = false;
72
+ this.removeListener('newListener', this.onData);
73
+ this.removeListener('resume', this.onResume);
74
+ nextTick(clonePiped, this);
75
+ }
76
+ }
77
+ onResume() {
78
+ this._hasListener = false;
79
+ this.removeListener('newListener', this.onData);
80
+ this.removeListener('resume', this.onResume);
81
+ nextTick(clonePiped, this);
82
+ }
83
+ resume() {
84
+ if (this._internalPipe) {
85
+ return this;
86
+ }
87
+ PassThrough.prototype.resume.call(this);
88
+ return this;
89
+ }
90
+ clone() {
91
+ if (!this._original) {
92
+ throw new Error('already started');
93
+ }
94
+ this._clonesCount++;
95
+ this.removeListener('newListener', this.onData);
96
+ this.removeListener('resume', this.onResume);
97
+ const clone = new StreamClone(this);
98
+ if (this._hasListener) {
99
+ this.on('newListener', this.onData);
100
+ this.on('resume', this.onResume);
101
+ }
102
+ return clone;
103
+ }
104
+ }
@@ -0,0 +1,52 @@
1
+ export const HTTP_CODE_MAP = {
2
+ OK: {
3
+ CODE: 200,
4
+ TEXT: 'OK'
5
+ },
6
+ NO_CONTENT: {
7
+ CODE: 204,
8
+ TEXT: 'NO CONTENT'
9
+ },
10
+ INTERNAL_SERVER_ERROR: {
11
+ CODE: 500,
12
+ TEXT: 'INTERNAL SERVER ERROR'
13
+ },
14
+ RESOURCE_NOT_FOUND: {
15
+ CODE: 404,
16
+ TEXT: 'RESOURCE NOT FOUND'
17
+ },
18
+ BAD_REQUEST: {
19
+ CODE: 400,
20
+ TEXT: 'BAD REQUEST'
21
+ },
22
+ UNAUTHORIZED: {
23
+ CODE: 401,
24
+ TEXT: 'UNAUTHORIZED'
25
+ },
26
+ CONFLICT: {
27
+ CODE: 409,
28
+ TEXT: 'CONFLICT, MAY BE YOU ARE TRYING TO CREATE A RESOURCE THAT ALREADY EXIST!'
29
+ },
30
+ FORBIDDEN: {
31
+ CODE: 403,
32
+ TEXT: 'FORBIDDEN, MAY BE YOUR USAGE REACHED MAX ALLOWED LIMIT!'
33
+ },
34
+ UNEXPECTED: {
35
+ CODE: 101,
36
+ TEXT: 'UNEXPECTED RESPONSE FOUND'
37
+ }
38
+ };
39
+ export const HTTP_HEADER_MAP = {
40
+ CONTENT_JSON: 'application/json; charset=utf-8',
41
+ AUTHORIZATION_KEY: 'Authorization'
42
+ };
43
+ export const REQUEST_PROPERTY = {
44
+ BLOB: 'blob'
45
+ };
46
+ export const X_ZCSRF_TOKEN = 'X-ZCSRF-TOKEN';
47
+ export const ZD_CSRPARAM = 'zd_csrparam';
48
+ const HTTP_CODE_REV_MAP = {};
49
+ const HTTP_CODE_MAP_KEYS = Object.keys(HTTP_CODE_MAP);
50
+ for (const KEY of HTTP_CODE_MAP_KEYS)
51
+ HTTP_CODE_REV_MAP[HTTP_CODE_MAP[KEY].CODE] = HTTP_CODE_MAP[KEY];
52
+ export { HTTP_CODE_REV_MAP };
@@ -0,0 +1,19 @@
1
+ export var ResponseType;
2
+ (function (ResponseType) {
3
+ ResponseType["RAW"] = "raw";
4
+ ResponseType["JSON"] = "json";
5
+ ResponseType["STRING"] = "string";
6
+ ResponseType["BUFFER"] = "buffer";
7
+ })(ResponseType || (ResponseType = {}));
8
+ export var RequestType;
9
+ (function (RequestType) {
10
+ RequestType["FILE"] = "file";
11
+ RequestType["JSON"] = "json";
12
+ RequestType["URL_ENCODED"] = "url_encoded";
13
+ RequestType["RAW"] = "raw";
14
+ })(RequestType || (RequestType = {}));
15
+ export var FormDataKeys;
16
+ (function (FormDataKeys) {
17
+ FormDataKeys["CODE"] = "code";
18
+ FormDataKeys["FILE_NAME"] = "file_name";
19
+ })(FormDataKeys || (FormDataKeys = {}));
@@ -0,0 +1,6 @@
1
+ import { PrefixedCatalystError } from '@zcatalyst/utils';
2
+ export class CatalystAPIError extends PrefixedCatalystError {
3
+ constructor(code, message, value, statusCode) {
4
+ super('app', code, message, value, statusCode);
5
+ }
6
+ }