@grandlinex/swagger-mate 1.3.3 → 1.3.5

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 (33) hide show
  1. package/dist/cjs/Swagger/Client/SwaggerClient.d.ts +0 -3
  2. package/dist/cjs/Swagger/Client/SwaggerClient.js +5 -38
  3. package/dist/cjs/index.d.ts +0 -1
  4. package/dist/cjs/index.js +0 -1
  5. package/dist/mjs/Swagger/Client/SwaggerClient.d.ts +0 -3
  6. package/dist/mjs/Swagger/Client/SwaggerClient.js +5 -38
  7. package/dist/mjs/index.d.ts +0 -1
  8. package/dist/mjs/index.js +0 -1
  9. package/package.json +7 -7
  10. package/res/templates/class/ApiCon.ts +1 -1
  11. package/res/templates/class/CApiCon.ts +1 -1
  12. package/res/templates/class/IApiCon.ts +1 -1
  13. package/res/templates/class/index.ts +2 -3
  14. package/dist/cjs/Swagger/debug/BaseCon.d.ts +0 -172
  15. package/dist/cjs/Swagger/debug/BaseCon.js +0 -380
  16. package/dist/cjs/Swagger/debug/FetchCon.d.ts +0 -3
  17. package/dist/cjs/Swagger/debug/FetchCon.js +0 -79
  18. package/dist/cjs/Swagger/debug/NodeCon.d.ts +0 -3
  19. package/dist/cjs/Swagger/debug/NodeCon.js +0 -158
  20. package/dist/cjs/Swagger/debug/index.d.ts +0 -5
  21. package/dist/cjs/Swagger/debug/index.js +0 -27
  22. package/dist/mjs/Swagger/debug/BaseCon.d.ts +0 -172
  23. package/dist/mjs/Swagger/debug/BaseCon.js +0 -373
  24. package/dist/mjs/Swagger/debug/FetchCon.d.ts +0 -3
  25. package/dist/mjs/Swagger/debug/FetchCon.js +0 -77
  26. package/dist/mjs/Swagger/debug/NodeCon.d.ts +0 -3
  27. package/dist/mjs/Swagger/debug/NodeCon.js +0 -120
  28. package/dist/mjs/Swagger/debug/index.d.ts +0 -5
  29. package/dist/mjs/Swagger/debug/index.js +0 -5
  30. package/res/templates/class/AxiosCon.ts +0 -49
  31. package/res/templates/class/BaseCon.ts +0 -476
  32. package/res/templates/class/FetchCon.ts +0 -93
  33. package/res/templates/class/NodeCon.ts +0 -172
@@ -1,120 +0,0 @@
1
- import FormData from 'form-data';
2
- import * as http from 'http';
3
- import * as https from 'https';
4
- function selectClient(url) {
5
- if (url.startsWith('https')) {
6
- return https;
7
- }
8
- return http;
9
- }
10
- async function fcTransform(message, raw) {
11
- let data = null;
12
- if (message.headers['content-type']?.includes('application/json')) {
13
- data = JSON.parse(raw);
14
- }
15
- else if (message.headers['content-type']?.includes('form-data')) {
16
- data = null; // await res.formData()
17
- }
18
- else if (message.headers['content-type']?.includes('octet-stream')) {
19
- data = Buffer.from(raw);
20
- }
21
- else if (message.headers['content-type']?.startsWith('text/')) {
22
- data = Buffer.from(raw).toString('utf8');
23
- }
24
- return {
25
- code: message.statusCode || -1,
26
- data,
27
- headers: message.headers,
28
- };
29
- }
30
- function bodyTransform(r, headers) {
31
- if (!r) {
32
- return {
33
- headers: headers || {},
34
- body: undefined,
35
- };
36
- }
37
- if (r instanceof FormData) {
38
- return {
39
- body: r,
40
- headers: {
41
- ...headers,
42
- 'content-type': 'multipart/form-data',
43
- },
44
- };
45
- }
46
- return {
47
- body: JSON.stringify(r),
48
- headers: {
49
- ...headers,
50
- 'content-type': 'application/json',
51
- },
52
- };
53
- }
54
- async function makeRequest(url, option, body, config) {
55
- return new Promise((resolve) => {
56
- let headers = config?.headers || {};
57
- let transForm = null;
58
- if (body) {
59
- let safeHeaders;
60
- if (option.headers &&
61
- typeof option.headers === 'object' &&
62
- !Array.isArray(option.headers)) {
63
- safeHeaders = option.headers;
64
- }
65
- transForm = bodyTransform(body, safeHeaders);
66
- headers = {
67
- ...headers,
68
- ...transForm.headers,
69
- };
70
- }
71
- const req = selectClient(url)
72
- .request(url, {
73
- headers,
74
- ...option,
75
- }, (res) => {
76
- let data = '';
77
- // A chunk of data has been received.
78
- res.on('data', (chunk) => {
79
- data += chunk;
80
- });
81
- // The whole response has been received. Print out the result.
82
- res.on('end', () => {
83
- resolve(fcTransform(res, data));
84
- });
85
- })
86
- .on('error', (err) => {
87
- console.log(`Error: ${err.message}`);
88
- resolve({
89
- code: -1,
90
- data: null,
91
- headers: {},
92
- });
93
- });
94
- if (transForm && transForm.body) {
95
- req.write(transForm.body);
96
- }
97
- req.end();
98
- });
99
- }
100
- const NodeCon = {
101
- get: async (url, config) => {
102
- return makeRequest(url, {}, undefined, config);
103
- },
104
- post: async (url, body, config) => {
105
- return makeRequest(url, {
106
- method: 'POST',
107
- }, body, config);
108
- },
109
- patch: async (url, body, config) => {
110
- return makeRequest(url, {
111
- method: 'PATCH',
112
- }, body, config);
113
- },
114
- delete: async (url, config) => {
115
- return makeRequest(url, {
116
- method: 'DELETE',
117
- }, undefined, config);
118
- },
119
- };
120
- export default NodeCon;
@@ -1,5 +0,0 @@
1
- import BaseCon from './BaseCon.js';
2
- import NodeCon from './NodeCon.js';
3
- import FetchCon from './FetchCon.js';
4
- export * from './BaseCon.js';
5
- export { NodeCon, FetchCon, BaseCon };
@@ -1,5 +0,0 @@
1
- import BaseCon from './BaseCon.js';
2
- import NodeCon from './NodeCon.js';
3
- import FetchCon from './FetchCon.js';
4
- export * from './BaseCon.js';
5
- export { NodeCon, FetchCon, BaseCon };
@@ -1,49 +0,0 @@
1
- import axios, { AxiosResponse } from 'axios';
2
- import { ConHandle, ConHandleResponse } from './BaseCon.js';
3
-
4
- async function acTransform<T>(
5
- r: Promise<AxiosResponse<T>>
6
- ): Promise<ConHandleResponse<T>> {
7
- const res = await r;
8
- return {
9
- code: res.status,
10
- data: res.data,
11
- headers: res.headers as Record<string, any>,
12
- };
13
- }
14
- const AxiosCon: ConHandle = {
15
- get: async (url, config) => {
16
- return acTransform(
17
- axios.get(url, {
18
- headers: config?.headers,
19
- validateStatus: (status) => true,
20
- })
21
- );
22
- },
23
- post: async (url, body, config) => {
24
- return acTransform(
25
- axios.post(url, body, {
26
- headers: config?.headers,
27
- validateStatus: (status) => true,
28
- })
29
- );
30
- },
31
- patch: async (url, body, config) => {
32
- return acTransform(
33
- axios.patch(url, body, {
34
- headers: config?.headers,
35
- validateStatus: (status) => true,
36
- })
37
- );
38
- },
39
- delete: async (url, config) => {
40
- return acTransform(
41
- axios.delete(url, {
42
- headers: config?.headers,
43
- validateStatus: (status) => true,
44
- })
45
- );
46
- },
47
- };
48
-
49
- export default AxiosCon;
@@ -1,476 +0,0 @@
1
- /**
2
- * THIS FILE IS AUTOMATICALLY GENERATED
3
- * DO NOT EDIT THIS FILE
4
- */
5
-
6
- import FormData from 'form-data';
7
-
8
- export type ErrorType = {
9
- type: string;
10
- global?: string[];
11
- field?: { key: string; message: string }[];
12
- };
13
-
14
- export type HeaderType = string | string[] | number | undefined;
15
- export type HandleRes<T> = {
16
- success: boolean;
17
- data: T | null;
18
- code?: number;
19
- error?: ErrorType;
20
- headers?: Record<string, HeaderType>;
21
- };
22
-
23
- export type PathParam = { [key: string]: string | number | undefined };
24
- export function isErrorType(x: any): x is ErrorType {
25
- return x && typeof x === 'object' && x.type === 'error';
26
- }
27
-
28
- export interface ConHandleConfig {
29
- headers?: Record<string, string>;
30
- param?: PathParam;
31
- query?: PathParam;
32
- }
33
- export interface ConHandleResponse<T> {
34
- code: number;
35
- data: T | null;
36
- headers: Record<string, HeaderType>;
37
- }
38
-
39
- export interface ConHandle {
40
- get<T>(url: string, config?: ConHandleConfig): Promise<ConHandleResponse<T>>;
41
- post<T, J>(
42
- url: string,
43
- body?: J,
44
- config?: ConHandleConfig,
45
- ): Promise<ConHandleResponse<T>>;
46
- patch<T, J>(
47
- url: string,
48
- body?: J,
49
- config?: ConHandleConfig,
50
- ): Promise<ConHandleResponse<T>>;
51
-
52
- delete<T>(
53
- url: string,
54
- config?: ConHandleConfig,
55
- ): Promise<ConHandleResponse<T>>;
56
- }
57
-
58
- /**
59
- * BaseCon provides a minimal client for interacting with an HTTP backend.
60
- * It manages connection state, authentication tokens, and reconnection
61
- * logic while delegating actual HTTP requests to a supplied {@link ConHandle}.
62
- *
63
- * @class
64
- */
65
- export default class BaseCon {
66
- private api: string;
67
-
68
- private permanentHeader: undefined | Record<string, string>;
69
-
70
- private authorization: string | null;
71
-
72
- private noAuth: boolean;
73
-
74
- private disconnected: boolean;
75
-
76
- private readonly logger: (arg: any) => void;
77
-
78
- con: ConHandle;
79
-
80
- reconnect: () => Promise<boolean>;
81
-
82
- onReconnect: (con: BaseCon) => Promise<boolean>;
83
-
84
- constructor(conf: {
85
- con: ConHandle;
86
- endpoint: string;
87
- logger?: (arg: any) => void;
88
- }) {
89
- this.api = conf.endpoint;
90
- this.logger = conf.logger ?? console.log;
91
- this.disconnected = true;
92
- this.noAuth = false;
93
- this.authorization = null;
94
- this.con = conf.con;
95
- this.reconnect = async () => {
96
- this.disconnected = true;
97
- return false;
98
- };
99
- this.onReconnect = () => Promise.resolve(true);
100
- this.handle = this.handle.bind(this);
101
- }
102
-
103
- /**
104
- * Retrieves the API endpoint.
105
- *
106
- * @return {string} The API endpoint string.
107
- */
108
- getApiEndpoint(): string {
109
- return this.api;
110
- }
111
-
112
- /**
113
- * Sets the API endpoint URL used by the client.
114
- *
115
- * @param {string} endpoint - The full URL of the API endpoint.
116
- * @returns {void}
117
- */
118
- setApiEndpoint(endpoint: string): void {
119
- this.api = endpoint;
120
- }
121
-
122
- /**
123
- * Indicates whether the instance is considered connected.
124
- *
125
- * The instance is regarded as connected when it either does not require authentication
126
- * (`noAuth` is true) or it has an authorization token set (`authorization` is not null),
127
- * and it is not currently marked as disconnected.
128
- *
129
- * @return {boolean} `true` if the instance is connected, `false` otherwise.
130
- */
131
- isConnected(): boolean {
132
- return (this.noAuth || this.authorization !== null) && !this.disconnected;
133
- }
134
-
135
- /**
136
- * Returns the current authorization token.
137
- *
138
- * @return {string} The authorization token or an empty string if none is set.
139
- */
140
- token(): string {
141
- return this.authorization || '';
142
- }
143
-
144
- private p(path: string, config?: ConHandleConfig) {
145
- let pp = path;
146
- if (config?.param) {
147
- const e = Object.keys(config.param);
148
- for (const d of e) {
149
- pp = pp.replace(`{${d}}`, `${config.param[d]}`);
150
- }
151
- }
152
- if (config?.query) {
153
- const e = Object.keys(config.query);
154
- const slices = [];
155
- for (const d of e) {
156
- if (config.query[d]) {
157
- slices.push(`${d}=${config.query[d]}`);
158
- }
159
- }
160
- if (slices.length > 0) {
161
- pp += `?${slices.join('&')}`;
162
- }
163
- }
164
- return `${this.api}${pp}`;
165
- }
166
-
167
- /**
168
- * Sends a ping request to the API to verify connectivity and version availability.
169
- *
170
- * @return {boolean} `true` if the API responded with a 200 status code and a valid version object; `false` otherwise.
171
- */
172
- async ping(): Promise<boolean> {
173
- try {
174
- const version = await this.con.get<{ api: number }>(this.p('/version'));
175
- return version.data?.api !== undefined && version.code === 200;
176
- } catch (e) {
177
- this.logger('ping failed');
178
- return false;
179
- }
180
- }
181
-
182
- /**
183
- * Validates the current authentication token by performing a ping and a test request
184
- * to the backend. The method first ensures connectivity via {@link ping}. If the ping
185
- * succeeds, it attempts to retrieve a token from the `/test/auth` endpoint using the
186
- * current token in the `Authorization` header. The operation is considered successful
187
- * if the response status code is 200 or 201.
188
- *
189
- * If any step fails, an error is logged and the method returns {@code false}. On
190
- * success, it returns {@code true}.
191
- *
192
- * @return {Promise<boolean>} A promise that resolves to {@code true} if the token
193
- * test succeeds, otherwise {@code false}.
194
- */
195
- async testToken(): Promise<boolean> {
196
- const ping = await this.ping();
197
- if (ping) {
198
- try {
199
- const con = await this.con.get<{ token: string }>(
200
- this.p('/test/auth'),
201
- {
202
- headers: {
203
- Authorization: this.token(),
204
- },
205
- },
206
- );
207
- return con.code === 200 || con.code === 201;
208
- } catch (e) {
209
- this.logger(e);
210
- this.logger('cant connect to backend');
211
- }
212
- }
213
- this.logger('test ping failed');
214
-
215
- return false;
216
- }
217
-
218
- /**
219
- * Attempts to establish a connection to the backend without authentication.
220
- *
221
- * This method sends a ping request. If the ping succeeds, it clears any
222
- * existing authorization data, marks the instance as connected,
223
- * enables the no‑authentication mode, and returns `true`. If the ping
224
- * fails, it logs a warning, clears authorization, marks the instance
225
- * as disconnected, and returns `false`.
226
- *
227
- * @return {Promise<boolean>} `true` when a connection is successfully
228
- * established without authentication, otherwise `false`.
229
- */
230
- async connectNoAuth(): Promise<boolean> {
231
- const ping = await this.ping();
232
- if (ping) {
233
- this.authorization = null;
234
- this.disconnected = false;
235
- this.noAuth = true;
236
- return true;
237
- }
238
- this.logger('cant connect to backend');
239
- this.authorization = null;
240
- this.disconnected = true;
241
- return false;
242
- }
243
-
244
- /**
245
- * Forces a connection using the provided bearer token.
246
- *
247
- * @param {string} token The token to be used for authentication.
248
- * @returns {void}
249
- */
250
- forceConnectWithToken(token: string): void {
251
- this.authorization = `Bearer ${token}`;
252
- this.disconnected = false;
253
- this.noAuth = false;
254
- }
255
-
256
- /**
257
- * Establishes a connection to the backend using the supplied credentials.
258
- * Performs a health‑check ping first; if successful, it requests an authentication
259
- * token from the `/token` endpoint. When the token is obtained, the method
260
- * updates internal state (authorization header, connection flags) and, unless
261
- * a dry run is requested, sets up a reconnection routine. Any errors are
262
- * logged and the method resolves to `false`.
263
- *
264
- * @param {string} email - The user's email address for authentication.
265
- * @param {string} pw - The password (or token) for the specified user.
266
- * @param {boolean} [dry=false] - If `true`, the method performs a dry run
267
- * without persisting credentials or configuring reconnection logic.
268
- *
269
- * @returns Promise<boolean> `true` if the connection was successfully
270
- * established, otherwise `false`.
271
- */
272
- async connect(
273
- email: string,
274
- pw: string,
275
- dry: boolean = false,
276
- ): Promise<boolean> {
277
- const ping = await this.ping();
278
- if (ping) {
279
- try {
280
- const token = await this.con.post<
281
- { token: string },
282
- {
283
- username: string;
284
- token: string;
285
- }
286
- >(this.p('/token'), {
287
- username: email,
288
- token: pw,
289
- });
290
- if (token.code === 200 || token.code === 201) {
291
- if (!dry) {
292
- this.authorization = `Bearer ${token.data?.token}`;
293
- this.disconnected = false;
294
- this.noAuth = false;
295
- this.reconnect = async () => {
296
- return (
297
- (await this.connect(email, pw)) && (await this.testToken())
298
- );
299
- };
300
- }
301
- return true;
302
- }
303
- } catch (e) {
304
- this.logger(e);
305
- }
306
- }
307
- this.logger('cant connect to backend');
308
- this.authorization = null;
309
- this.disconnected = true;
310
- this.noAuth = false;
311
- return false;
312
- }
313
-
314
- /**
315
- * Performs an HTTP request using the client’s internal connection.
316
- *
317
- * The method verifies that the client is connected before attempting a request.
318
- * It automatically injects the authorization token, permanent headers, and any
319
- * headers supplied in `config`. If the request body is a `FormData` instance
320
- * (or provides a `getHeaders` method), the appropriate form headers are added.
321
- *
322
- * Response handling:
323
- * - `200` or `201`: returns `success: true` with the received data.
324
- * - `498`: attempts to reconnect and retries the request once.
325
- * - `401`: logs an authentication error, marks the client as disconnected.
326
- * - `403` and other status codes: return `success: false` with the status code.
327
- *
328
- * @param {'POST'|'GET'|'PATCH'|'DELETE'} type The HTTP method to use.
329
- * @param {string} path The endpoint path relative to the base URL.
330
- * @param {J} [body] Optional request payload. May be `FormData` or a plain object.
331
- * @param {ConHandleConfig} [config] Optional Axios-like configuration for the request.
332
- * @returns {Promise<HandleRes<T>>} A promise that resolves to a `HandleRes` object
333
- * containing the response data, status code, any error information, and headers.
334
- */
335
- async handle<T, J>(
336
- type: 'POST' | 'GET' | 'PATCH' | 'DELETE',
337
- path: string,
338
- body?: J,
339
- config?: ConHandleConfig,
340
- ): Promise<HandleRes<T>> {
341
- if (!this.isConnected()) {
342
- this.logger('Disconnected');
343
- return {
344
- success: false,
345
- data: null,
346
- code: -1,
347
- };
348
- }
349
- let formHeader = null;
350
- const cK = body as any;
351
- if (
352
- cK &&
353
- (cK instanceof FormData || typeof cK?.getHeaders === 'function')
354
- ) {
355
- formHeader = cK?.getHeaders?.() || {};
356
- } else {
357
- formHeader = {};
358
- }
359
-
360
- let dat: ConHandleResponse<T> | null;
361
- switch (type) {
362
- case 'GET':
363
- dat = await this.con.get<T>(this.p(path, config), {
364
- ...config,
365
- headers: {
366
- Authorization: this.token(),
367
- ...formHeader,
368
- ...config?.headers,
369
- ...this.permanentHeader,
370
- },
371
- });
372
- break;
373
- case 'POST':
374
- dat = await this.con.post<T, J>(this.p(path, config), body, {
375
- ...config,
376
- headers: {
377
- Authorization: this.token(),
378
- ...formHeader,
379
- ...config?.headers,
380
- ...this.permanentHeader,
381
- },
382
- });
383
- break;
384
- case 'PATCH':
385
- dat = await this.con.patch<T, J>(this.p(path, config), body, {
386
- ...config,
387
- headers: {
388
- Authorization: this.token(),
389
- ...formHeader,
390
- ...config?.headers,
391
- ...this.permanentHeader,
392
- },
393
- });
394
- break;
395
- case 'DELETE':
396
- dat = await this.con.delete<T>(this.p(path, config), {
397
- ...config,
398
- headers: {
399
- Authorization: this.token(),
400
- ...formHeader,
401
- ...config?.headers,
402
- ...this.permanentHeader,
403
- },
404
- });
405
- break;
406
- default:
407
- return {
408
- success: false,
409
- data: null,
410
- code: -1,
411
- };
412
- }
413
-
414
- let error: ErrorType | undefined;
415
- if (isErrorType(dat.data)) {
416
- error = dat.data;
417
- }
418
- let x = false;
419
- switch (dat.code) {
420
- case 200:
421
- case 201:
422
- return {
423
- success: true,
424
- data: dat.data,
425
- code: dat.code,
426
- error,
427
- headers: dat.headers,
428
- };
429
- case 498:
430
- x = await this.reconnect();
431
- if (x) {
432
- this.onReconnect(this).catch((dx) => {
433
- this.logger(dx);
434
- });
435
- return this.handle(type, path, body, config);
436
- }
437
- this.reconnect = async () => {
438
- this.disconnected = true;
439
- return false;
440
- };
441
- this.disconnected = true;
442
- return {
443
- success: false,
444
- data: null,
445
- code: dat.code,
446
- error,
447
- headers: dat.headers,
448
- };
449
- case 401:
450
- this.logger('AUTH NOT VALID');
451
- return {
452
- success: false,
453
- data: null,
454
- code: dat.code,
455
- error,
456
- headers: dat.headers,
457
- };
458
- case 403:
459
- return {
460
- success: false,
461
- data: null,
462
- error,
463
- code: dat.code,
464
- headers: dat.headers,
465
- };
466
- default:
467
- return {
468
- success: false,
469
- data: null,
470
- error,
471
- code: dat.code,
472
- headers: dat.headers,
473
- };
474
- }
475
- }
476
- }