@grandlinex/swagger-mate 1.3.1 → 1.3.2

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.
@@ -6,13 +6,20 @@ import FormData from 'form-data';
6
6
  export function isErrorType(x) {
7
7
  return x && typeof x === 'object' && x.type === 'error';
8
8
  }
9
+ /**
10
+ * BaseCon provides a minimal client for interacting with an HTTP backend.
11
+ * It manages connection state, authentication tokens, and reconnection
12
+ * logic while delegating actual HTTP requests to a supplied {@link ConHandle}.
13
+ *
14
+ * @class
15
+ */
9
16
  export default class BaseCon {
10
17
  constructor(conf) {
11
18
  this.api = conf.endpoint;
12
- this.logger = conf.logger || console.log;
19
+ this.logger = conf.logger ?? console.log;
13
20
  this.disconnected = true;
21
+ this.noAuth = false;
14
22
  this.authorization = null;
15
- this.failFlag = false;
16
23
  this.con = conf.con;
17
24
  this.reconnect = async () => {
18
25
  this.disconnected = true;
@@ -21,10 +28,40 @@ export default class BaseCon {
21
28
  this.onReconnect = () => Promise.resolve(true);
22
29
  this.handle = this.handle.bind(this);
23
30
  }
24
- // Class helper functions
31
+ /**
32
+ * Retrieves the API endpoint.
33
+ *
34
+ * @return {string} The API endpoint string.
35
+ */
36
+ getApiEndpoint() {
37
+ return this.api;
38
+ }
39
+ /**
40
+ * Sets the API endpoint URL used by the client.
41
+ *
42
+ * @param {string} endpoint - The full URL of the API endpoint.
43
+ * @returns {void}
44
+ */
45
+ setApiEndpoint(endpoint) {
46
+ this.api = endpoint;
47
+ }
48
+ /**
49
+ * Indicates whether the instance is considered connected.
50
+ *
51
+ * The instance is regarded as connected when it either does not require authentication
52
+ * (`noAuth` is true) or it has an authorization token set (`authorization` is not null),
53
+ * and it is not currently marked as disconnected.
54
+ *
55
+ * @return {boolean} `true` if the instance is connected, `false` otherwise.
56
+ */
25
57
  isConnected() {
26
- return this.authorization !== null && !this.disconnected;
58
+ return (this.noAuth || this.authorization !== null) && !this.disconnected;
27
59
  }
60
+ /**
61
+ * Returns the current authorization token.
62
+ *
63
+ * @return {string} The authorization token or an empty string if none is set.
64
+ */
28
65
  token() {
29
66
  return this.authorization || '';
30
67
  }
@@ -50,35 +87,34 @@ export default class BaseCon {
50
87
  }
51
88
  return `${this.api}${pp}`;
52
89
  }
90
+ /**
91
+ * Sends a ping request to the API to verify connectivity and version availability.
92
+ *
93
+ * @return {boolean} `true` if the API responded with a 200 status code and a valid version object; `false` otherwise.
94
+ */
53
95
  async ping() {
54
96
  try {
55
97
  const version = await this.con.get(this.p('/version'));
56
- return version.data?.api === 1 && version.code === 200;
98
+ return version.data?.api !== undefined && version.code === 200;
57
99
  }
58
100
  catch (e) {
59
101
  this.logger('ping failed');
60
102
  return false;
61
103
  }
62
104
  }
63
- async test(email, password) {
64
- const ping = await this.ping();
65
- if (ping) {
66
- try {
67
- this.logger({ email, password });
68
- const con = await this.con.post(this.p('/token'), {
69
- username: email,
70
- token: password,
71
- });
72
- return con.code === 200 || con.code === 201;
73
- }
74
- catch (e) {
75
- this.logger(e);
76
- this.logger('cant connect to backend');
77
- }
78
- }
79
- this.logger('test ping failed');
80
- return false;
81
- }
105
+ /**
106
+ * Validates the current authentication token by performing a ping and a test request
107
+ * to the backend. The method first ensures connectivity via {@link ping}. If the ping
108
+ * succeeds, it attempts to retrieve a token from the `/test/auth` endpoint using the
109
+ * current token in the `Authorization` header. The operation is considered successful
110
+ * if the response status code is 200 or 201.
111
+ *
112
+ * If any step fails, an error is logged and the method returns {@code false}. On
113
+ * success, it returns {@code true}.
114
+ *
115
+ * @return {Promise<boolean>} A promise that resolves to {@code true} if the token
116
+ * test succeeds, otherwise {@code false}.
117
+ */
82
118
  async testToken() {
83
119
  const ping = await this.ping();
84
120
  if (ping) {
@@ -98,7 +134,59 @@ export default class BaseCon {
98
134
  this.logger('test ping failed');
99
135
  return false;
100
136
  }
101
- async connect(email, pw) {
137
+ /**
138
+ * Attempts to establish a connection to the backend without authentication.
139
+ *
140
+ * This method sends a ping request. If the ping succeeds, it clears any
141
+ * existing authorization data, marks the instance as connected,
142
+ * enables the no‑authentication mode, and returns `true`. If the ping
143
+ * fails, it logs a warning, clears authorization, marks the instance
144
+ * as disconnected, and returns `false`.
145
+ *
146
+ * @return {Promise<boolean>} `true` when a connection is successfully
147
+ * established without authentication, otherwise `false`.
148
+ */
149
+ async connectNoAuth() {
150
+ const ping = await this.ping();
151
+ if (ping) {
152
+ this.authorization = null;
153
+ this.disconnected = false;
154
+ this.noAuth = true;
155
+ return true;
156
+ }
157
+ this.logger('cant connect to backend');
158
+ this.authorization = null;
159
+ this.disconnected = true;
160
+ return false;
161
+ }
162
+ /**
163
+ * Forces a connection using the provided bearer token.
164
+ *
165
+ * @param {string} token The token to be used for authentication.
166
+ * @returns {void}
167
+ */
168
+ forceConnectWithToken(token) {
169
+ this.authorization = `Bearer ${token}`;
170
+ this.disconnected = false;
171
+ this.noAuth = false;
172
+ }
173
+ /**
174
+ * Establishes a connection to the backend using the supplied credentials.
175
+ * Performs a health‑check ping first; if successful, it requests an authentication
176
+ * token from the `/token` endpoint. When the token is obtained, the method
177
+ * updates internal state (authorization header, connection flags) and, unless
178
+ * a dry run is requested, sets up a reconnection routine. Any errors are
179
+ * logged and the method resolves to `false`.
180
+ *
181
+ * @param {string} email - The user's email address for authentication.
182
+ * @param {string} pw - The password (or token) for the specified user.
183
+ * @param {boolean} [dry=false] - If `true`, the method performs a dry run
184
+ * without persisting credentials or configuring reconnection logic.
185
+ *
186
+ * @returns Promise<boolean> `true` if the connection was successfully
187
+ * established, otherwise `false`.
188
+ */
189
+ async connect(email, pw, dry = false) {
102
190
  const ping = await this.ping();
103
191
  if (ping) {
104
192
  try {
@@ -106,13 +194,15 @@ export default class BaseCon {
106
194
  username: email,
107
195
  token: pw,
108
196
  });
109
- // TODO check token
110
197
  if (token.code === 200 || token.code === 201) {
111
- this.authorization = `Bearer ${token.data?.token}`;
112
- this.disconnected = false;
113
- this.reconnect = async () => {
114
- return (await this.connect(email, pw)) && (await this.testToken());
115
- };
198
+ if (!dry) {
199
+ this.authorization = `Bearer ${token.data?.token}`;
200
+ this.disconnected = false;
201
+ this.noAuth = false;
202
+ this.reconnect = async () => {
203
+ return ((await this.connect(email, pw)) && (await this.testToken()));
204
+ };
205
+ }
116
206
  return true;
117
207
  }
118
208
  }
@@ -123,17 +213,32 @@ export default class BaseCon {
123
213
  this.logger('cant connect to backend');
124
214
  this.authorization = null;
125
215
  this.disconnected = true;
216
+ this.noAuth = false;
126
217
  return false;
127
218
  }
128
219
  /**
129
- * Enable client before auth
220
+ * Performs an HTTP request using the client’s internal connection.
221
+ *
222
+ * The method verifies that the client is connected before attempting a request.
223
+ * It automatically injects the authorization token, permanent headers, and any
224
+ * headers supplied in `config`. If the request body is a `FormData` instance
225
+ * (or provides a `getHeaders` method), the appropriate form headers are added.
226
+ *
227
+ * Response handling:
228
+ * - `200` or `201`: returns `success: true` with the received data.
229
+ * - `498`: attempts to reconnect and retries the request once.
230
+ * - `401`: logs an authentication error, marks the client as disconnected.
231
+ * - `403` and other status codes: return `success: false` with the status code.
232
+ *
233
+ * @param {'POST'|'GET'|'PATCH'|'DELETE'} type The HTTP method to use.
234
+ * @param {string} path The endpoint path relative to the base URL.
235
+ * @param {J} [body] Optional request payload. May be `FormData` or a plain object.
236
+ * @param {ConHandleConfig} [config] Optional Axios-like configuration for the request.
237
+ * @returns {Promise<HandleRes<T>>} A promise that resolves to a `HandleRes` object
238
+ * containing the response data, status code, any error information, and headers.
130
239
  */
131
- fakeEnableClient() {
132
- this.authorization = 'DEBUG';
133
- this.disconnected = false;
134
- }
135
240
  async handle(type, path, body, config) {
136
- if (!this.authorization || this.disconnected) {
241
+ if (!this.isConnected()) {
137
242
  this.logger('Disconnected');
138
243
  return {
139
244
  success: false,
@@ -240,7 +345,6 @@ export default class BaseCon {
240
345
  };
241
346
  case 401:
242
347
  this.logger('AUTH NOT VALID');
243
- this.disconnected = true;
244
348
  return {
245
349
  success: false,
246
350
  data: null,
package/dist/mjs/cli.js CHANGED
@@ -38,7 +38,11 @@ async function run() {
38
38
  console.log('Serving Swagger Meta');
39
39
  const auth = process.env.SW_AUTH || undefined;
40
40
  const port = process.env.SW_PORT || undefined;
41
- SwaggerUtil.serveMeta(conf, port ? parseInt(port, 10) : undefined, auth);
41
+ SwaggerUtil.serveMeta(conf, {
42
+ port: port ? parseInt(port, 10) : undefined,
43
+ auth,
44
+ type: 'rapi-doc',
45
+ });
42
46
  }
43
47
  if (arg[arg.length - 2] === '--build') {
44
48
  console.log('Building Swagger Meta');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grandlinex/swagger-mate",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -70,7 +70,7 @@
70
70
  "ts-jest": "29.3.4",
71
71
  "ts-loader": "9.5.2",
72
72
  "ts-node": "10.9.2",
73
- "typedoc": "0.28.15",
73
+ "typedoc": "0.28.16",
74
74
  "typescript": "5.9.2"
75
75
  }
76
76
  }
@@ -0,0 +1,28 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <script type="module" src="./rapidoc-min.js"></script>
6
+ <script defer="defer" src="./rapidoc-min.js"></script>
7
+ </head>
8
+ <body>
9
+ <rapi-doc id="thedoc"
10
+ spec-url="/spec"
11
+ allow-server-selection="true"
12
+ allow-authentication="true"
13
+ theme="dark"
14
+ render-style="focused"
15
+ show-header="false"
16
+ show-operation-id="true"
17
+ primary-color="#02802C"
18
+ bg-color="#121212"
19
+ text-color="#f2f3f4"
20
+ show-method-in-nav-bar="as-colored-text"
21
+ schema-style="table"
22
+ nav-text-color="#f2f3f4"
23
+ api-key-name="Authorization"
24
+ api-key-location="header">
25
+ <!--api-key-value="Bearer ${token}"-->
26
+ </rapi-doc>
27
+ </body>
28
+ </html>