@almina-capital/ef-broker-typed-api 2.0.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.
@@ -0,0 +1,486 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+ /*
4
+ * ---------------------------------------------------------------
5
+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
6
+ * ## ##
7
+ * ## AUTHOR: acacode ##
8
+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
9
+ * ---------------------------------------------------------------
10
+ */
11
+
12
+ /** Article of list */
13
+ export interface ArticleSchema {
14
+ id?: number;
15
+ title?: string;
16
+ image?: string;
17
+ slug?: string;
18
+ text?: string;
19
+ link?: string;
20
+ category?: string;
21
+ /** @format date-time */
22
+ createdAt?: string;
23
+ published?: boolean;
24
+ }
25
+
26
+ /** Paginated List */
27
+ export interface PaginatedArticleListSchema {
28
+ total?: number;
29
+ pages?: number;
30
+ limit?: number;
31
+ page?: number;
32
+ items?: ArticleSchema[];
33
+ }
34
+
35
+ /** User */
36
+ export interface UserSchema {
37
+ /** @example "+79114445566" */
38
+ phone: string;
39
+ /** @example "Alex" */
40
+ firstName: string;
41
+ /** @example "email@google.com" */
42
+ email?: string | null;
43
+ }
44
+
45
+ export interface ArticleShowSchema {
46
+ id?: number;
47
+ title?: string;
48
+ h1?: string;
49
+ h2?: string;
50
+ image?: string;
51
+ slug?: string;
52
+ link?: string;
53
+ category?: string;
54
+ /** @format date-time */
55
+ createdAt?: string;
56
+ text?: string;
57
+ published?: boolean;
58
+ }
59
+
60
+ /** error */
61
+ export interface ErrorSchema {
62
+ /**
63
+ * type of message
64
+ * @example "error"
65
+ */
66
+ type?: string;
67
+ /**
68
+ * error field
69
+ * @example "field"
70
+ */
71
+ field?: string;
72
+ /**
73
+ * error message
74
+ * @example "invalid field"
75
+ */
76
+ message?: string;
77
+ }
78
+
79
+ export type QueryParamsType = Record<string | number, any>;
80
+ export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
81
+
82
+ export interface FullRequestParams extends Omit<RequestInit, "body"> {
83
+ /** set parameter to `true` for call `securityWorker` for this request */
84
+ secure?: boolean;
85
+ /** request path */
86
+ path: string;
87
+ /** content type of request body */
88
+ type?: ContentType;
89
+ /** query params */
90
+ query?: QueryParamsType;
91
+ /** format of response (i.e. response.json() -> format: "json") */
92
+ format?: ResponseFormat;
93
+ /** request body */
94
+ body?: unknown;
95
+ /** base url */
96
+ baseUrl?: string;
97
+ /** request cancellation token */
98
+ cancelToken?: CancelToken;
99
+ }
100
+
101
+ export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
102
+
103
+ export interface ApiConfig<SecurityDataType = unknown> {
104
+ baseUrl?: string;
105
+ baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
106
+ securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
107
+ customFetch?: typeof fetch;
108
+ }
109
+
110
+ export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
111
+ data: D;
112
+ error: E;
113
+ }
114
+
115
+ type CancelToken = Symbol | string | number;
116
+
117
+ export enum ContentType {
118
+ Json = "application/json",
119
+ FormData = "multipart/form-data",
120
+ UrlEncoded = "application/x-www-form-urlencoded",
121
+ Text = "text/plain",
122
+ }
123
+
124
+ export class HttpClient<SecurityDataType = unknown> {
125
+ public baseUrl: string = "";
126
+ private securityData: SecurityDataType | null = null;
127
+ private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
128
+ private abortControllers = new Map<CancelToken, AbortController>();
129
+ private customFetch = (...fetchParams: Parameters<typeof fetch>) => fetch(...fetchParams);
130
+
131
+ private baseApiParams: RequestParams = {
132
+ credentials: "same-origin",
133
+ headers: {},
134
+ redirect: "follow",
135
+ referrerPolicy: "no-referrer",
136
+ };
137
+
138
+ constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
139
+ Object.assign(this, apiConfig);
140
+ }
141
+
142
+ public setSecurityData = (data: SecurityDataType | null) => {
143
+ this.securityData = data;
144
+ };
145
+
146
+ protected encodeQueryParam(key: string, value: any) {
147
+ const encodedKey = encodeURIComponent(key);
148
+ return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
149
+ }
150
+
151
+ protected addQueryParam(query: QueryParamsType, key: string) {
152
+ return this.encodeQueryParam(key, query[key]);
153
+ }
154
+
155
+ protected addArrayQueryParam(query: QueryParamsType, key: string) {
156
+ const value = query[key];
157
+ return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");
158
+ }
159
+
160
+ protected toQueryString(rawQuery?: QueryParamsType): string {
161
+ const query = rawQuery || {};
162
+ const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
163
+ return keys
164
+ .map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key)))
165
+ .join("&");
166
+ }
167
+
168
+ protected addQueryParams(rawQuery?: QueryParamsType): string {
169
+ const queryString = this.toQueryString(rawQuery);
170
+ return queryString ? `?${queryString}` : "";
171
+ }
172
+
173
+ private contentFormatters: Record<ContentType, (input: any) => any> = {
174
+ [ContentType.Json]: (input: any) =>
175
+ input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
176
+ [ContentType.Text]: (input: any) => (input !== null && typeof input !== "string" ? JSON.stringify(input) : input),
177
+ [ContentType.FormData]: (input: any) =>
178
+ Object.keys(input || {}).reduce((formData, key) => {
179
+ const property = input[key];
180
+ formData.append(
181
+ key,
182
+ property instanceof Blob
183
+ ? property
184
+ : typeof property === "object" && property !== null
185
+ ? JSON.stringify(property)
186
+ : `${property}`,
187
+ );
188
+ return formData;
189
+ }, new FormData()),
190
+ [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
191
+ };
192
+
193
+ protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
194
+ return {
195
+ ...this.baseApiParams,
196
+ ...params1,
197
+ ...(params2 || {}),
198
+ headers: {
199
+ ...(this.baseApiParams.headers || {}),
200
+ ...(params1.headers || {}),
201
+ ...((params2 && params2.headers) || {}),
202
+ },
203
+ };
204
+ }
205
+
206
+ protected createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
207
+ if (this.abortControllers.has(cancelToken)) {
208
+ const abortController = this.abortControllers.get(cancelToken);
209
+ if (abortController) {
210
+ return abortController.signal;
211
+ }
212
+ return void 0;
213
+ }
214
+
215
+ const abortController = new AbortController();
216
+ this.abortControllers.set(cancelToken, abortController);
217
+ return abortController.signal;
218
+ };
219
+
220
+ public abortRequest = (cancelToken: CancelToken) => {
221
+ const abortController = this.abortControllers.get(cancelToken);
222
+
223
+ if (abortController) {
224
+ abortController.abort();
225
+ this.abortControllers.delete(cancelToken);
226
+ }
227
+ };
228
+
229
+ public request = async <T = any, E = any>({
230
+ body,
231
+ secure,
232
+ path,
233
+ type,
234
+ query,
235
+ format,
236
+ baseUrl,
237
+ cancelToken,
238
+ ...params
239
+ }: FullRequestParams): Promise<HttpResponse<T, E>> => {
240
+ const secureParams =
241
+ ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
242
+ this.securityWorker &&
243
+ (await this.securityWorker(this.securityData))) ||
244
+ {};
245
+ const requestParams = this.mergeRequestParams(params, secureParams);
246
+ const queryString = query && this.toQueryString(query);
247
+ const payloadFormatter = this.contentFormatters[type || ContentType.Json];
248
+ const responseFormat = format || requestParams.format;
249
+
250
+ return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
251
+ ...requestParams,
252
+ headers: {
253
+ ...(requestParams.headers || {}),
254
+ ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
255
+ },
256
+ signal: cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal,
257
+ body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
258
+ }).then(async (response) => {
259
+ const r = response as HttpResponse<T, E>;
260
+ r.data = null as unknown as T;
261
+ r.error = null as unknown as E;
262
+
263
+ const data = !responseFormat
264
+ ? r
265
+ : await response[responseFormat]()
266
+ .then((data) => {
267
+ if (r.ok) {
268
+ r.data = data;
269
+ } else {
270
+ r.error = data;
271
+ }
272
+ return r;
273
+ })
274
+ .catch((e) => {
275
+ r.error = e;
276
+ return r;
277
+ });
278
+
279
+ if (cancelToken) {
280
+ this.abortControllers.delete(cancelToken);
281
+ }
282
+
283
+ if (!response.ok) throw data;
284
+ return data;
285
+ });
286
+ };
287
+ }
288
+
289
+ /**
290
+ * @title Ef-broker API
291
+ * @version 0.1
292
+ *
293
+ * Ef-broker
294
+ */
295
+ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
296
+ /**
297
+ * @description Status page
298
+ *
299
+ * @name EfbrokerControllerStatusControllerStatus
300
+ * @summary Status page
301
+ * @request GET:/
302
+ */
303
+ efbrokerControllerStatusControllerStatus = (params: RequestParams = {}) =>
304
+ this.request<
305
+ {
306
+ /**
307
+ * @format string
308
+ * @example "unstable"
309
+ */
310
+ version?: any;
311
+ /**
312
+ * @format integer
313
+ * @example 1595596886
314
+ */
315
+ time?: any;
316
+ },
317
+ any
318
+ >({
319
+ path: `/`,
320
+ method: "GET",
321
+ format: "json",
322
+ ...params,
323
+ });
324
+
325
+ admin = {
326
+ /**
327
+ * @description Article list
328
+ *
329
+ * @name EfbrokerControllerAdminArticleControllerList
330
+ * @request GET:/admin/article
331
+ */
332
+ efbrokerControllerAdminArticleControllerList: (
333
+ query?: {
334
+ /** @example "search" */
335
+ search?: string;
336
+ /** @example "category" */
337
+ category?: string;
338
+ /** @example 1 */
339
+ page?: number;
340
+ /** @example 20 */
341
+ limit?: number;
342
+ },
343
+ params: RequestParams = {},
344
+ ) =>
345
+ this.request<PaginatedArticleListSchema, any>({
346
+ path: `/admin/article`,
347
+ method: "GET",
348
+ query: query,
349
+ format: "json",
350
+ ...params,
351
+ }),
352
+
353
+ /**
354
+ * @description Create new article
355
+ *
356
+ * @name EfbrokerControllerAdminArticleControllerAdd
357
+ * @request POST:/admin/article
358
+ */
359
+ efbrokerControllerAdminArticleControllerAdd: (data: ArticleShowSchema, params: RequestParams = {}) =>
360
+ this.request<ArticleShowSchema, any>({
361
+ path: `/admin/article`,
362
+ method: "POST",
363
+ body: data,
364
+ type: ContentType.Json,
365
+ format: "json",
366
+ ...params,
367
+ }),
368
+
369
+ /**
370
+ * @description Upload new file
371
+ *
372
+ * @name EfbrokerControllerAdminArticleControllerUpload
373
+ * @request POST:/admin/article/upload
374
+ */
375
+ efbrokerControllerAdminArticleControllerUpload: (data: ArticleShowSchema, params: RequestParams = {}) =>
376
+ this.request<any, any>({
377
+ path: `/admin/article/upload`,
378
+ method: "POST",
379
+ body: data,
380
+ type: ContentType.Json,
381
+ format: "json",
382
+ ...params,
383
+ }),
384
+
385
+ /**
386
+ * @description Get article by id
387
+ *
388
+ * @name EfbrokerControllerAdminArticleControllerShow
389
+ * @request GET:/admin/article/{id}
390
+ */
391
+ efbrokerControllerAdminArticleControllerShow: (id: number, params: RequestParams = {}) =>
392
+ this.request<PaginatedArticleListSchema, any>({
393
+ path: `/admin/article/${id}`,
394
+ method: "GET",
395
+ format: "json",
396
+ ...params,
397
+ }),
398
+
399
+ /**
400
+ * @description Update article by id
401
+ *
402
+ * @name EfbrokerControllerAdminArticleControllerEdit
403
+ * @request PUT:/admin/article/{id}
404
+ */
405
+ efbrokerControllerAdminArticleControllerEdit: (id: number, data: ArticleShowSchema, params: RequestParams = {}) =>
406
+ this.request<ArticleShowSchema, ErrorSchema>({
407
+ path: `/admin/article/${id}`,
408
+ method: "PUT",
409
+ body: data,
410
+ type: ContentType.Json,
411
+ format: "json",
412
+ ...params,
413
+ }),
414
+
415
+ /**
416
+ * @description Delete article by id
417
+ *
418
+ * @name EfbrokerControllerAdminArticleControllerDelete
419
+ * @request DELETE:/admin/article/{id}
420
+ */
421
+ efbrokerControllerAdminArticleControllerDelete: (id: number, params: RequestParams = {}) =>
422
+ this.request<any, any>({
423
+ path: `/admin/article/${id}`,
424
+ method: "DELETE",
425
+ format: "json",
426
+ ...params,
427
+ }),
428
+ };
429
+ public = {
430
+ /**
431
+ * @description Article list
432
+ *
433
+ * @name EfbrokerControllerArticleControllerList
434
+ * @request GET:/public/article
435
+ */
436
+ efbrokerControllerArticleControllerList: (
437
+ query?: {
438
+ /** @example "search" */
439
+ search?: string;
440
+ /** @example "category" */
441
+ category?: string;
442
+ /** @example 1 */
443
+ page?: number;
444
+ /** @example 20 */
445
+ limit?: number;
446
+ },
447
+ params: RequestParams = {},
448
+ ) =>
449
+ this.request<PaginatedArticleListSchema, any>({
450
+ path: `/public/article`,
451
+ method: "GET",
452
+ query: query,
453
+ format: "json",
454
+ ...params,
455
+ }),
456
+
457
+ /**
458
+ * @description Get article by slug
459
+ *
460
+ * @name EfbrokerControllerArticleControllerShowBySlug
461
+ * @request GET:/public/article/{slug}
462
+ */
463
+ efbrokerControllerArticleControllerShowBySlug: (slug: string, params: RequestParams = {}) =>
464
+ this.request<ArticleShowSchema, any>({
465
+ path: `/public/article/${slug}`,
466
+ method: "GET",
467
+ format: "json",
468
+ ...params,
469
+ }),
470
+
471
+ /**
472
+ * @description Create user
473
+ *
474
+ * @name EfbrokerControllerUserControllerCreate
475
+ * @request POST:/public/user
476
+ */
477
+ efbrokerControllerUserControllerCreate: (data: UserSchema, params: RequestParams = {}) =>
478
+ this.request<void, void>({
479
+ path: `/public/user`,
480
+ method: "POST",
481
+ body: data,
482
+ type: ContentType.Json,
483
+ ...params,
484
+ }),
485
+ };
486
+ }
package/index.d.ts ADDED
@@ -0,0 +1,486 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+ /*
4
+ * ---------------------------------------------------------------
5
+ * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
6
+ * ## ##
7
+ * ## AUTHOR: acacode ##
8
+ * ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
9
+ * ---------------------------------------------------------------
10
+ */
11
+
12
+ /** Article of list */
13
+ export interface ArticleSchema {
14
+ id?: number;
15
+ title?: string;
16
+ image?: string;
17
+ slug?: string;
18
+ text?: string;
19
+ link?: string;
20
+ category?: string;
21
+ /** @format date-time */
22
+ createdAt?: string;
23
+ published?: boolean;
24
+ }
25
+
26
+ /** Paginated List */
27
+ export interface PaginatedArticleListSchema {
28
+ total?: number;
29
+ pages?: number;
30
+ limit?: number;
31
+ page?: number;
32
+ items?: ArticleSchema[];
33
+ }
34
+
35
+ /** User */
36
+ export interface UserSchema {
37
+ /** @example "+79114445566" */
38
+ phone: string;
39
+ /** @example "Alex" */
40
+ firstName: string;
41
+ /** @example "email@google.com" */
42
+ email?: string | null;
43
+ }
44
+
45
+ export interface ArticleShowSchema {
46
+ id?: number;
47
+ title?: string;
48
+ h1?: string;
49
+ h2?: string;
50
+ image?: string;
51
+ slug?: string;
52
+ link?: string;
53
+ category?: string;
54
+ /** @format date-time */
55
+ createdAt?: string;
56
+ text?: string;
57
+ published?: boolean;
58
+ }
59
+
60
+ /** error */
61
+ export interface ErrorSchema {
62
+ /**
63
+ * type of message
64
+ * @example "error"
65
+ */
66
+ type?: string;
67
+ /**
68
+ * error field
69
+ * @example "field"
70
+ */
71
+ field?: string;
72
+ /**
73
+ * error message
74
+ * @example "invalid field"
75
+ */
76
+ message?: string;
77
+ }
78
+
79
+ export type QueryParamsType = Record<string | number, any>;
80
+ export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
81
+
82
+ export interface FullRequestParams extends Omit<RequestInit, "body"> {
83
+ /** set parameter to `true` for call `securityWorker` for this request */
84
+ secure?: boolean;
85
+ /** request path */
86
+ path: string;
87
+ /** content type of request body */
88
+ type?: ContentType;
89
+ /** query params */
90
+ query?: QueryParamsType;
91
+ /** format of response (i.e. response.json() -> format: "json") */
92
+ format?: ResponseFormat;
93
+ /** request body */
94
+ body?: unknown;
95
+ /** base url */
96
+ baseUrl?: string;
97
+ /** request cancellation token */
98
+ cancelToken?: CancelToken;
99
+ }
100
+
101
+ export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
102
+
103
+ export interface ApiConfig<SecurityDataType = unknown> {
104
+ baseUrl?: string;
105
+ baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
106
+ securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
107
+ customFetch?: typeof fetch;
108
+ }
109
+
110
+ export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
111
+ data: D;
112
+ error: E;
113
+ }
114
+
115
+ type CancelToken = Symbol | string | number;
116
+
117
+ export enum ContentType {
118
+ Json = "application/json",
119
+ FormData = "multipart/form-data",
120
+ UrlEncoded = "application/x-www-form-urlencoded",
121
+ Text = "text/plain",
122
+ }
123
+
124
+ export class HttpClient<SecurityDataType = unknown> {
125
+ public baseUrl: string = "";
126
+ private securityData: SecurityDataType | null = null;
127
+ private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
128
+ private abortControllers = new Map<CancelToken, AbortController>();
129
+ private customFetch = (...fetchParams: Parameters<typeof fetch>) => fetch(...fetchParams);
130
+
131
+ private baseApiParams: RequestParams = {
132
+ credentials: "same-origin",
133
+ headers: {},
134
+ redirect: "follow",
135
+ referrerPolicy: "no-referrer",
136
+ };
137
+
138
+ constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
139
+ Object.assign(this, apiConfig);
140
+ }
141
+
142
+ public setSecurityData = (data: SecurityDataType | null) => {
143
+ this.securityData = data;
144
+ };
145
+
146
+ protected encodeQueryParam(key: string, value: any) {
147
+ const encodedKey = encodeURIComponent(key);
148
+ return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
149
+ }
150
+
151
+ protected addQueryParam(query: QueryParamsType, key: string) {
152
+ return this.encodeQueryParam(key, query[key]);
153
+ }
154
+
155
+ protected addArrayQueryParam(query: QueryParamsType, key: string) {
156
+ const value = query[key];
157
+ return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");
158
+ }
159
+
160
+ protected toQueryString(rawQuery?: QueryParamsType): string {
161
+ const query = rawQuery || {};
162
+ const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
163
+ return keys
164
+ .map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key)))
165
+ .join("&");
166
+ }
167
+
168
+ protected addQueryParams(rawQuery?: QueryParamsType): string {
169
+ const queryString = this.toQueryString(rawQuery);
170
+ return queryString ? `?${queryString}` : "";
171
+ }
172
+
173
+ private contentFormatters: Record<ContentType, (input: any) => any> = {
174
+ [ContentType.Json]: (input: any) =>
175
+ input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
176
+ [ContentType.Text]: (input: any) => (input !== null && typeof input !== "string" ? JSON.stringify(input) : input),
177
+ [ContentType.FormData]: (input: any) =>
178
+ Object.keys(input || {}).reduce((formData, key) => {
179
+ const property = input[key];
180
+ formData.append(
181
+ key,
182
+ property instanceof Blob
183
+ ? property
184
+ : typeof property === "object" && property !== null
185
+ ? JSON.stringify(property)
186
+ : `${property}`,
187
+ );
188
+ return formData;
189
+ }, new FormData()),
190
+ [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
191
+ };
192
+
193
+ protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
194
+ return {
195
+ ...this.baseApiParams,
196
+ ...params1,
197
+ ...(params2 || {}),
198
+ headers: {
199
+ ...(this.baseApiParams.headers || {}),
200
+ ...(params1.headers || {}),
201
+ ...((params2 && params2.headers) || {}),
202
+ },
203
+ };
204
+ }
205
+
206
+ protected createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
207
+ if (this.abortControllers.has(cancelToken)) {
208
+ const abortController = this.abortControllers.get(cancelToken);
209
+ if (abortController) {
210
+ return abortController.signal;
211
+ }
212
+ return void 0;
213
+ }
214
+
215
+ const abortController = new AbortController();
216
+ this.abortControllers.set(cancelToken, abortController);
217
+ return abortController.signal;
218
+ };
219
+
220
+ public abortRequest = (cancelToken: CancelToken) => {
221
+ const abortController = this.abortControllers.get(cancelToken);
222
+
223
+ if (abortController) {
224
+ abortController.abort();
225
+ this.abortControllers.delete(cancelToken);
226
+ }
227
+ };
228
+
229
+ public request = async <T = any, E = any>({
230
+ body,
231
+ secure,
232
+ path,
233
+ type,
234
+ query,
235
+ format,
236
+ baseUrl,
237
+ cancelToken,
238
+ ...params
239
+ }: FullRequestParams): Promise<HttpResponse<T, E>> => {
240
+ const secureParams =
241
+ ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
242
+ this.securityWorker &&
243
+ (await this.securityWorker(this.securityData))) ||
244
+ {};
245
+ const requestParams = this.mergeRequestParams(params, secureParams);
246
+ const queryString = query && this.toQueryString(query);
247
+ const payloadFormatter = this.contentFormatters[type || ContentType.Json];
248
+ const responseFormat = format || requestParams.format;
249
+
250
+ return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
251
+ ...requestParams,
252
+ headers: {
253
+ ...(requestParams.headers || {}),
254
+ ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
255
+ },
256
+ signal: cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal,
257
+ body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
258
+ }).then(async (response) => {
259
+ const r = response as HttpResponse<T, E>;
260
+ r.data = null as unknown as T;
261
+ r.error = null as unknown as E;
262
+
263
+ const data = !responseFormat
264
+ ? r
265
+ : await response[responseFormat]()
266
+ .then((data) => {
267
+ if (r.ok) {
268
+ r.data = data;
269
+ } else {
270
+ r.error = data;
271
+ }
272
+ return r;
273
+ })
274
+ .catch((e) => {
275
+ r.error = e;
276
+ return r;
277
+ });
278
+
279
+ if (cancelToken) {
280
+ this.abortControllers.delete(cancelToken);
281
+ }
282
+
283
+ if (!response.ok) throw data;
284
+ return data;
285
+ });
286
+ };
287
+ }
288
+
289
+ /**
290
+ * @title Ef-broker API
291
+ * @version 0.1
292
+ *
293
+ * Ef-broker
294
+ */
295
+ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
296
+ /**
297
+ * @description Status page
298
+ *
299
+ * @name EfbrokerControllerStatusControllerStatus
300
+ * @summary Status page
301
+ * @request GET:/
302
+ */
303
+ efbrokerControllerStatusControllerStatus = (params: RequestParams = {}) =>
304
+ this.request<
305
+ {
306
+ /**
307
+ * @format string
308
+ * @example "unstable"
309
+ */
310
+ version?: any;
311
+ /**
312
+ * @format integer
313
+ * @example 1595596886
314
+ */
315
+ time?: any;
316
+ },
317
+ any
318
+ >({
319
+ path: `/`,
320
+ method: "GET",
321
+ format: "json",
322
+ ...params,
323
+ });
324
+
325
+ admin = {
326
+ /**
327
+ * @description Article list
328
+ *
329
+ * @name EfbrokerControllerAdminArticleControllerList
330
+ * @request GET:/admin/article
331
+ */
332
+ efbrokerControllerAdminArticleControllerList: (
333
+ query?: {
334
+ /** @example "search" */
335
+ search?: string;
336
+ /** @example "category" */
337
+ category?: string;
338
+ /** @example 1 */
339
+ page?: number;
340
+ /** @example 20 */
341
+ limit?: number;
342
+ },
343
+ params: RequestParams = {},
344
+ ) =>
345
+ this.request<PaginatedArticleListSchema, any>({
346
+ path: `/admin/article`,
347
+ method: "GET",
348
+ query: query,
349
+ format: "json",
350
+ ...params,
351
+ }),
352
+
353
+ /**
354
+ * @description Create new article
355
+ *
356
+ * @name EfbrokerControllerAdminArticleControllerAdd
357
+ * @request POST:/admin/article
358
+ */
359
+ efbrokerControllerAdminArticleControllerAdd: (data: ArticleShowSchema, params: RequestParams = {}) =>
360
+ this.request<ArticleShowSchema, any>({
361
+ path: `/admin/article`,
362
+ method: "POST",
363
+ body: data,
364
+ type: ContentType.Json,
365
+ format: "json",
366
+ ...params,
367
+ }),
368
+
369
+ /**
370
+ * @description Upload new file
371
+ *
372
+ * @name EfbrokerControllerAdminArticleControllerUpload
373
+ * @request POST:/admin/article/upload
374
+ */
375
+ efbrokerControllerAdminArticleControllerUpload: (data: ArticleShowSchema, params: RequestParams = {}) =>
376
+ this.request<any, any>({
377
+ path: `/admin/article/upload`,
378
+ method: "POST",
379
+ body: data,
380
+ type: ContentType.Json,
381
+ format: "json",
382
+ ...params,
383
+ }),
384
+
385
+ /**
386
+ * @description Get article by id
387
+ *
388
+ * @name EfbrokerControllerAdminArticleControllerShow
389
+ * @request GET:/admin/article/{id}
390
+ */
391
+ efbrokerControllerAdminArticleControllerShow: (id: number, params: RequestParams = {}) =>
392
+ this.request<PaginatedArticleListSchema, any>({
393
+ path: `/admin/article/${id}`,
394
+ method: "GET",
395
+ format: "json",
396
+ ...params,
397
+ }),
398
+
399
+ /**
400
+ * @description Update article by id
401
+ *
402
+ * @name EfbrokerControllerAdminArticleControllerEdit
403
+ * @request PUT:/admin/article/{id}
404
+ */
405
+ efbrokerControllerAdminArticleControllerEdit: (id: number, data: ArticleShowSchema, params: RequestParams = {}) =>
406
+ this.request<ArticleShowSchema, ErrorSchema>({
407
+ path: `/admin/article/${id}`,
408
+ method: "PUT",
409
+ body: data,
410
+ type: ContentType.Json,
411
+ format: "json",
412
+ ...params,
413
+ }),
414
+
415
+ /**
416
+ * @description Delete article by id
417
+ *
418
+ * @name EfbrokerControllerAdminArticleControllerDelete
419
+ * @request DELETE:/admin/article/{id}
420
+ */
421
+ efbrokerControllerAdminArticleControllerDelete: (id: number, params: RequestParams = {}) =>
422
+ this.request<any, any>({
423
+ path: `/admin/article/${id}`,
424
+ method: "DELETE",
425
+ format: "json",
426
+ ...params,
427
+ }),
428
+ };
429
+ public = {
430
+ /**
431
+ * @description Article list
432
+ *
433
+ * @name EfbrokerControllerArticleControllerList
434
+ * @request GET:/public/article
435
+ */
436
+ efbrokerControllerArticleControllerList: (
437
+ query?: {
438
+ /** @example "search" */
439
+ search?: string;
440
+ /** @example "category" */
441
+ category?: string;
442
+ /** @example 1 */
443
+ page?: number;
444
+ /** @example 20 */
445
+ limit?: number;
446
+ },
447
+ params: RequestParams = {},
448
+ ) =>
449
+ this.request<PaginatedArticleListSchema, any>({
450
+ path: `/public/article`,
451
+ method: "GET",
452
+ query: query,
453
+ format: "json",
454
+ ...params,
455
+ }),
456
+
457
+ /**
458
+ * @description Get article by slug
459
+ *
460
+ * @name EfbrokerControllerArticleControllerShowBySlug
461
+ * @request GET:/public/article/{slug}
462
+ */
463
+ efbrokerControllerArticleControllerShowBySlug: (slug: string, params: RequestParams = {}) =>
464
+ this.request<ArticleShowSchema, any>({
465
+ path: `/public/article/${slug}`,
466
+ method: "GET",
467
+ format: "json",
468
+ ...params,
469
+ }),
470
+
471
+ /**
472
+ * @description Create user
473
+ *
474
+ * @name EfbrokerControllerUserControllerCreate
475
+ * @request POST:/public/user
476
+ */
477
+ efbrokerControllerUserControllerCreate: (data: UserSchema, params: RequestParams = {}) =>
478
+ this.request<void, void>({
479
+ path: `/public/user`,
480
+ method: "POST",
481
+ body: data,
482
+ type: ContentType.Json,
483
+ ...params,
484
+ }),
485
+ };
486
+ }
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import {makeApi} from './src/generator.js';
2
+ import {download} from './src/download.js';
3
+
4
+ download('https://api.ef-broker.ru/open-api.yaml', 'open-api.yaml', function () {
5
+ makeApi()
6
+ })
7
+ makeApi()
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@almina-capital/ef-broker-typed-api",
3
+ "version": "2.0.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "",
8
+ "main": "index.js",
9
+ "type": "module",
10
+ "scripts": {
11
+ "generate": "node index.js"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git@bitbucket.org:tadeon/ef-broker-typed-api.git"
16
+ },
17
+ "author": "",
18
+ "license": "ISC",
19
+ "dependencies": {
20
+ "@types/node": "^18.11.9",
21
+ "axios": "^1.2.0",
22
+ "lodash": "^4.17.21",
23
+ "node-fetch": "^3.3.0",
24
+ "request": "^2.88.2",
25
+ "swagger-typescript-api": "^12.0.2",
26
+ "typescript": "^4.9.4"
27
+ }
28
+ }
@@ -0,0 +1,27 @@
1
+ import fs from "fs";
2
+ import http from "https";
3
+
4
+ export const download = (url, dest, cb) => {
5
+ const file = fs.createWriteStream(dest);
6
+
7
+ const request = http.get(url, (response) => {
8
+ // check if response is success
9
+ if (response.statusCode !== 200) {
10
+ return cb('Response status was ' + response.statusCode);
11
+ }
12
+ console.log('response', response)
13
+ response.pipe(file);
14
+ });
15
+
16
+ // close() is async, call cb after close completes
17
+ file.on('finish', () => file.close(cb));
18
+
19
+ // check for request error too
20
+ request.on('error', (err) => {
21
+ fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
22
+ });
23
+
24
+ file.on('error', (err) => { // Handle errors
25
+ fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
26
+ });
27
+ };
@@ -0,0 +1,135 @@
1
+ import {generateApi} from "swagger-typescript-api";
2
+ import path from "path";
3
+ import _ from "lodash";
4
+
5
+ export const makeApi = () => generateApi({
6
+ name: "index.d.ts",
7
+ output: path.resolve(process.cwd(), "./"),
8
+ input: path.resolve(process.cwd(), './open-api.yaml'),
9
+ generateUnionEnums: false,
10
+ enumNamesAsValues: false,
11
+ extractEnums: true,
12
+ codeGenConstructs: (struct) => ({
13
+ Keyword: {
14
+ Number: "number",
15
+ String: "string",
16
+ Boolean: "boolean",
17
+ Any: "any",
18
+ Void: "void",
19
+ Unknown: "unknown",
20
+ Null: "null",
21
+ Undefined: "undefined",
22
+ Object: "object",
23
+ File: "File",
24
+ Date: "Date",
25
+ Type: "type",
26
+ Enum: "enum",
27
+ Interface: "interface",
28
+ Array: "Array",
29
+ Record: "Record",
30
+ Intersection: "&",
31
+ Union: "|",
32
+ },
33
+ CodeGenKeyword: {
34
+ UtilRequiredKeys: "UtilRequiredKeys",
35
+ },
36
+ // /**
37
+ // * $A[] or Array<$A>
38
+ // */
39
+ // ArrayType: (content) => {
40
+ // if (this.anotherArrayType) {
41
+ // return `Array<${content}>`;
42
+ // }
43
+ //
44
+ // return `(${content})[]`;
45
+ // },
46
+ /**
47
+ * "$A"
48
+ */
49
+ StringValue: (content) => `"${content}"`,
50
+ /**
51
+ * $A
52
+ */
53
+ BooleanValue: (content) => `${content}`,
54
+ /**
55
+ * $A
56
+ */
57
+ NumberValue: (content) => `${content}`,
58
+ /**
59
+ * $A
60
+ */
61
+ NullValue: (content) => content,
62
+ /**
63
+ * $A1 | $A2
64
+ */
65
+ UnionType: (contents) => _.join(_.uniq(contents), ` | `),
66
+ /**
67
+ * ($A1)
68
+ */
69
+ ExpressionGroup: (content) => (content ? `(${content})` : ""),
70
+ /**
71
+ * $A1 & $A2
72
+ */
73
+ IntersectionType: (contents) => _.join(_.uniq(contents), ` & `),
74
+ /**
75
+ * Record<$A1, $A2>
76
+ */
77
+ RecordType: (key, value) => `Record<${key}, ${value}>`,
78
+ /**
79
+ * readonly $key?:$value
80
+ */
81
+ TypeField: ({ readonly, key, optional, value }) =>
82
+ _.compact([readonly && "readonly ", key, optional && "?", ": ", value]).join(""),
83
+ /**
84
+ * [key: $A1]: $A2
85
+ */
86
+ InterfaceDynamicField: (key, value) => `[key: ${key}]: ${value}`,
87
+ /**
88
+ * $A1 = $A2
89
+ */
90
+ EnumField: (key, value) => `${key} = ${value}`,
91
+ /**
92
+ * $A0.key = $A0.value,
93
+ * $A1.key = $A1.value,
94
+ * $AN.key = $AN.value,
95
+ */
96
+ EnumFieldsWrapper: (contents) =>
97
+ _.map(contents, ({ key, value }) => ` ${key} = ${value}`).join(",\n"),
98
+ /**
99
+ * {\n $A \n}
100
+ */
101
+ ObjectWrapper: (content) => `{\n${content}\n}`,
102
+ /**
103
+ * /** $A *\/
104
+ */
105
+ MultilineComment: (contents, formatFn) =>
106
+ [
107
+ ...(contents.length === 1
108
+ ? [`/** ${contents[0]} */`]
109
+ : ["/**", ...contents.map((content) => ` * ${content}`), " */"]),
110
+ ].map((part) => `${formatFn ? formatFn(part) : part}\n`),
111
+ /**
112
+ * $A1<...$A2.join(,)>
113
+ */
114
+ TypeWithGeneric: (typeName, genericArgs) => {
115
+ return `${typeName}${genericArgs.length ? `<${genericArgs.join(",")}>` : ""}`;
116
+ },
117
+ }),
118
+ hooks: {
119
+ onFormatRouteName: (routeInfo, templateRouteName) => {
120
+ if (!routeInfo.operationId) {
121
+ return ''
122
+ }
123
+
124
+ return templateRouteName; // this is generated route name from swagger-typescript-api
125
+ },
126
+ }
127
+ })
128
+ // .then(({ files, configuration }) => {
129
+ // files.forEach(({ content, name }) => {
130
+ // fs.writeFile(name, content, {}, function () {
131
+ // console.log('✅ !!!generation finished!!!')
132
+ // });
133
+ // });
134
+ // })
135
+ // .catch(e => console.error(e))