@createiq/backend 1.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.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ ## @createiq/backend
2
+
3
+ Automatically generated TypeScript types from OpenAPI specification.
4
+
5
+ Generated by @createiq/swagger-ts
@@ -0,0 +1,21 @@
1
+ import type { ApiRequestOptions } from './ApiRequestOptions';
2
+ import type { ApiResult } from './ApiResult';
3
+
4
+ export class ApiError extends Error {
5
+ public readonly url: string;
6
+ public readonly status: number;
7
+ public readonly statusText: string;
8
+ public readonly body: unknown;
9
+ public readonly request: ApiRequestOptions;
10
+
11
+ constructor(request: ApiRequestOptions, response: ApiResult, message: string) {
12
+ super(message);
13
+
14
+ this.name = 'ApiError';
15
+ this.url = response.url;
16
+ this.status = response.status;
17
+ this.statusText = response.statusText;
18
+ this.body = response.body;
19
+ this.request = request;
20
+ }
21
+ }
@@ -0,0 +1,21 @@
1
+ export type ApiRequestOptions<T = unknown> = {
2
+ readonly body?: any;
3
+ readonly cookies?: Record<string, unknown>;
4
+ readonly errors?: Record<number | string, string>;
5
+ readonly formData?: Record<string, unknown> | any[] | Blob | File;
6
+ readonly headers?: Record<string, unknown>;
7
+ readonly mediaType?: string;
8
+ readonly method:
9
+ | 'DELETE'
10
+ | 'GET'
11
+ | 'HEAD'
12
+ | 'OPTIONS'
13
+ | 'PATCH'
14
+ | 'POST'
15
+ | 'PUT';
16
+ readonly path?: Record<string, unknown>;
17
+ readonly query?: Record<string, unknown>;
18
+ readonly responseHeader?: string;
19
+ readonly responseTransformer?: (data: unknown) => Promise<T>;
20
+ readonly url: string;
21
+ };
@@ -0,0 +1,7 @@
1
+ export type ApiResult<TData = any> = {
2
+ readonly body: TData;
3
+ readonly ok: boolean;
4
+ readonly status: number;
5
+ readonly statusText: string;
6
+ readonly url: string;
7
+ };
@@ -0,0 +1,126 @@
1
+ export class CancelError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ this.name = 'CancelError';
5
+ }
6
+
7
+ public get isCancelled(): boolean {
8
+ return true;
9
+ }
10
+ }
11
+
12
+ export interface OnCancel {
13
+ readonly isResolved: boolean;
14
+ readonly isRejected: boolean;
15
+ readonly isCancelled: boolean;
16
+
17
+ (cancelHandler: () => void): void;
18
+ }
19
+
20
+ export class CancelablePromise<T> implements Promise<T> {
21
+ private _isResolved: boolean;
22
+ private _isRejected: boolean;
23
+ private _isCancelled: boolean;
24
+ readonly cancelHandlers: (() => void)[];
25
+ readonly promise: Promise<T>;
26
+ private _resolve?: (value: T | PromiseLike<T>) => void;
27
+ private _reject?: (reason?: unknown) => void;
28
+
29
+ constructor(
30
+ executor: (
31
+ resolve: (value: T | PromiseLike<T>) => void,
32
+ reject: (reason?: unknown) => void,
33
+ onCancel: OnCancel
34
+ ) => void
35
+ ) {
36
+ this._isResolved = false;
37
+ this._isRejected = false;
38
+ this._isCancelled = false;
39
+ this.cancelHandlers = [];
40
+ this.promise = new Promise<T>((resolve, reject) => {
41
+ this._resolve = resolve;
42
+ this._reject = reject;
43
+
44
+ const onResolve = (value: T | PromiseLike<T>): void => {
45
+ if (this._isResolved || this._isRejected || this._isCancelled) {
46
+ return;
47
+ }
48
+ this._isResolved = true;
49
+ if (this._resolve) this._resolve(value);
50
+ };
51
+
52
+ const onReject = (reason?: unknown): void => {
53
+ if (this._isResolved || this._isRejected || this._isCancelled) {
54
+ return;
55
+ }
56
+ this._isRejected = true;
57
+ if (this._reject) this._reject(reason);
58
+ };
59
+
60
+ const onCancel = (cancelHandler: () => void): void => {
61
+ if (this._isResolved || this._isRejected || this._isCancelled) {
62
+ return;
63
+ }
64
+ this.cancelHandlers.push(cancelHandler);
65
+ };
66
+
67
+ Object.defineProperty(onCancel, 'isResolved', {
68
+ get: (): boolean => this._isResolved,
69
+ });
70
+
71
+ Object.defineProperty(onCancel, 'isRejected', {
72
+ get: (): boolean => this._isRejected,
73
+ });
74
+
75
+ Object.defineProperty(onCancel, 'isCancelled', {
76
+ get: (): boolean => this._isCancelled,
77
+ });
78
+
79
+ return executor(onResolve, onReject, onCancel as OnCancel);
80
+ });
81
+ }
82
+
83
+ get [Symbol.toStringTag]() {
84
+ return "Cancellable Promise";
85
+ }
86
+
87
+ public then<TResult1 = T, TResult2 = never>(
88
+ onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
89
+ onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null
90
+ ): Promise<TResult1 | TResult2> {
91
+ return this.promise.then(onFulfilled, onRejected);
92
+ }
93
+
94
+ public catch<TResult = never>(
95
+ onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null
96
+ ): Promise<T | TResult> {
97
+ return this.promise.catch(onRejected);
98
+ }
99
+
100
+ public finally(onFinally?: (() => void) | null): Promise<T> {
101
+ return this.promise.finally(onFinally);
102
+ }
103
+
104
+ public cancel(): void {
105
+ if (this._isResolved || this._isRejected || this._isCancelled) {
106
+ return;
107
+ }
108
+ this._isCancelled = true;
109
+ if (this.cancelHandlers.length) {
110
+ try {
111
+ for (const cancelHandler of this.cancelHandlers) {
112
+ cancelHandler();
113
+ }
114
+ } catch (error) {
115
+ console.warn('Cancellation threw an error', error);
116
+ return;
117
+ }
118
+ }
119
+ this.cancelHandlers.length = 0;
120
+ if (this._reject) this._reject(new CancelError('Request aborted'));
121
+ }
122
+
123
+ public get isCancelled(): boolean {
124
+ return this._isCancelled;
125
+ }
126
+ }
@@ -0,0 +1,56 @@
1
+ import type { ApiRequestOptions } from './ApiRequestOptions';
2
+
3
+ type Headers = Record<string, string>;
4
+ type Middleware<T> = (value: T) => T | Promise<T>;
5
+ type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>;
6
+
7
+ export class Interceptors<T> {
8
+ _fns: Middleware<T>[];
9
+
10
+ constructor() {
11
+ this._fns = [];
12
+ }
13
+
14
+ eject(fn: Middleware<T>): void {
15
+ const index = this._fns.indexOf(fn);
16
+ if (index !== -1) {
17
+ this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)];
18
+ }
19
+ }
20
+
21
+ use(fn: Middleware<T>): void {
22
+ this._fns = [...this._fns, fn];
23
+ }
24
+ }
25
+
26
+ export type OpenAPIConfig = {
27
+ BASE: string;
28
+ CREDENTIALS: 'include' | 'omit' | 'same-origin';
29
+ ENCODE_PATH?: ((path: string) => string) | undefined;
30
+ HEADERS?: Headers | Resolver<Headers> | undefined;
31
+ PASSWORD?: string | Resolver<string> | undefined;
32
+ TOKEN?: string | Resolver<string> | undefined;
33
+ USERNAME?: string | Resolver<string> | undefined;
34
+ VERSION: string;
35
+ WITH_CREDENTIALS: boolean;
36
+ interceptors: {
37
+ request: Interceptors<RequestInit>;
38
+ response: Interceptors<Response>;
39
+ };
40
+ };
41
+
42
+ export const OpenAPI: OpenAPIConfig = {
43
+ BASE: '',
44
+ CREDENTIALS: 'include',
45
+ ENCODE_PATH: undefined,
46
+ HEADERS: undefined,
47
+ PASSWORD: undefined,
48
+ TOKEN: undefined,
49
+ USERNAME: undefined,
50
+ VERSION: '1.1',
51
+ WITH_CREDENTIALS: false,
52
+ interceptors: {
53
+ request: new Interceptors(),
54
+ response: new Interceptors(),
55
+ },
56
+ };
@@ -0,0 +1,350 @@
1
+ import { ApiError } from './ApiError';
2
+ import type { ApiRequestOptions } from './ApiRequestOptions';
3
+ import type { ApiResult } from './ApiResult';
4
+ import { CancelablePromise } from './CancelablePromise';
5
+ import type { OnCancel } from './CancelablePromise';
6
+ import type { OpenAPIConfig } from './OpenAPI';
7
+
8
+ export const isString = (value: unknown): value is string => {
9
+ return typeof value === 'string';
10
+ };
11
+
12
+ export const isStringWithValue = (value: unknown): value is string => {
13
+ return isString(value) && value !== '';
14
+ };
15
+
16
+ export const isBlob = (value: any): value is Blob => {
17
+ return value instanceof Blob;
18
+ };
19
+
20
+ export const isFormData = (value: unknown): value is FormData => {
21
+ return value instanceof FormData;
22
+ };
23
+
24
+ export const base64 = (str: string): string => {
25
+ try {
26
+ return btoa(str);
27
+ } catch (err) {
28
+ // @ts-ignore
29
+ return Buffer.from(str).toString('base64');
30
+ }
31
+ };
32
+
33
+ export const getQueryString = (params: Record<string, unknown>): string => {
34
+ const qs: string[] = [];
35
+
36
+ const append = (key: string, value: unknown) => {
37
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
38
+ };
39
+
40
+ const encodePair = (key: string, value: unknown) => {
41
+ if (value === undefined || value === null) {
42
+ return;
43
+ }
44
+
45
+ if (value instanceof Date) {
46
+ append(key, value.toISOString());
47
+ } else if (Array.isArray(value)) {
48
+ value.forEach(v => encodePair(key, v));
49
+ } else if (typeof value === 'object') {
50
+ Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v));
51
+ } else {
52
+ append(key, value);
53
+ }
54
+ };
55
+
56
+ Object.entries(params).forEach(([key, value]) => encodePair(key, value));
57
+
58
+ return qs.length ? `?${qs.join('&')}` : '';
59
+ };
60
+
61
+ const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
62
+ const encoder = config.ENCODE_PATH || encodeURI;
63
+
64
+ const path = options.url
65
+ .replace('{api-version}', config.VERSION)
66
+ .replace(/{(.*?)}/g, (substring: string, group: string) => {
67
+ if (options.path?.hasOwnProperty(group)) {
68
+ return encoder(String(options.path[group]));
69
+ }
70
+ return substring;
71
+ });
72
+
73
+ const url = config.BASE + path;
74
+ return options.query ? url + getQueryString(options.query) : url;
75
+ };
76
+
77
+ export const getFormData = (options: ApiRequestOptions): FormData | undefined => {
78
+ if (options.formData) {
79
+ const formData = new FormData();
80
+
81
+ const process = (key: string, value: unknown) => {
82
+ if (isString(value) || isBlob(value)) {
83
+ formData.append(key, value);
84
+ } else {
85
+ formData.append(key, JSON.stringify(value));
86
+ }
87
+ };
88
+
89
+ Object.entries(options.formData)
90
+ .filter(([, value]) => value !== undefined && value !== null)
91
+ .forEach(([key, value]) => {
92
+ if (Array.isArray(value)) {
93
+ value.forEach(v => process(key, v));
94
+ } else {
95
+ process(key, value);
96
+ }
97
+ });
98
+
99
+ return formData;
100
+ }
101
+ return undefined;
102
+ };
103
+
104
+ type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>;
105
+
106
+ export const resolve = async <T>(options: ApiRequestOptions<T>, resolver?: T | Resolver<T>): Promise<T | undefined> => {
107
+ if (typeof resolver === 'function') {
108
+ return (resolver as Resolver<T>)(options);
109
+ }
110
+ return resolver;
111
+ };
112
+
113
+ export const getHeaders = async <T>(config: OpenAPIConfig, options: ApiRequestOptions<T>): Promise<Headers> => {
114
+ const [token, username, password, additionalHeaders] = await Promise.all([
115
+ // @ts-ignore
116
+ resolve(options, config.TOKEN),
117
+ // @ts-ignore
118
+ resolve(options, config.USERNAME),
119
+ // @ts-ignore
120
+ resolve(options, config.PASSWORD),
121
+ // @ts-ignore
122
+ resolve(options, config.HEADERS),
123
+ ]);
124
+
125
+ const headers = Object.entries({
126
+ Accept: 'application/json',
127
+ ...additionalHeaders,
128
+ ...options.headers,
129
+ })
130
+ .filter(([, value]) => value !== undefined && value !== null)
131
+ .reduce((headers, [key, value]) => ({
132
+ ...headers,
133
+ [key]: String(value),
134
+ }), {} as Record<string, string>);
135
+
136
+ if (isStringWithValue(token)) {
137
+ headers['Authorization'] = `Bearer ${token}`;
138
+ }
139
+
140
+ if (isStringWithValue(username) && isStringWithValue(password)) {
141
+ const credentials = base64(`${username}:${password}`);
142
+ headers['Authorization'] = `Basic ${credentials}`;
143
+ }
144
+
145
+ if (options.body !== undefined) {
146
+ if (options.mediaType) {
147
+ headers['Content-Type'] = options.mediaType;
148
+ } else if (isBlob(options.body)) {
149
+ headers['Content-Type'] = options.body.type || 'application/octet-stream';
150
+ } else if (isString(options.body)) {
151
+ headers['Content-Type'] = 'text/plain';
152
+ } else if (!isFormData(options.body)) {
153
+ headers['Content-Type'] = 'application/json';
154
+ }
155
+ }
156
+
157
+ return new Headers(headers);
158
+ };
159
+
160
+ export const getRequestBody = (options: ApiRequestOptions): unknown => {
161
+ if (options.body !== undefined) {
162
+ if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) {
163
+ return JSON.stringify(options.body);
164
+ } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
165
+ return options.body;
166
+ } else {
167
+ return JSON.stringify(options.body);
168
+ }
169
+ }
170
+ return undefined;
171
+ };
172
+
173
+ export const sendRequest = async (
174
+ config: OpenAPIConfig,
175
+ options: ApiRequestOptions,
176
+ url: string,
177
+ body: any,
178
+ formData: FormData | undefined,
179
+ headers: Headers,
180
+ onCancel: OnCancel
181
+ ): Promise<Response> => {
182
+ const controller = new AbortController();
183
+
184
+ let request: RequestInit = {
185
+ headers,
186
+ body: body ?? formData,
187
+ method: options.method,
188
+ signal: controller.signal,
189
+ };
190
+
191
+ if (config.WITH_CREDENTIALS) {
192
+ request.credentials = config.CREDENTIALS;
193
+ }
194
+
195
+ for (const fn of config.interceptors.request._fns) {
196
+ request = await fn(request);
197
+ }
198
+
199
+ onCancel(() => controller.abort());
200
+
201
+ return await fetch(url, request);
202
+ };
203
+
204
+ export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => {
205
+ if (responseHeader) {
206
+ const content = response.headers.get(responseHeader);
207
+ if (isString(content)) {
208
+ return content;
209
+ }
210
+ }
211
+ return undefined;
212
+ };
213
+
214
+ export const getResponseBody = async (response: Response): Promise<unknown> => {
215
+ if (response.status !== 204) {
216
+ try {
217
+ const contentType = response.headers.get('Content-Type');
218
+ if (contentType) {
219
+ const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/'];
220
+ if (contentType.includes('application/json') || contentType.includes('+json')) {
221
+ return await response.json();
222
+ } else if (binaryTypes.some(type => contentType.includes(type))) {
223
+ return await response.blob();
224
+ } else if (contentType.includes('multipart/form-data')) {
225
+ return await response.formData();
226
+ } else if (contentType.includes('text/')) {
227
+ return await response.text();
228
+ }
229
+ }
230
+ } catch (error) {
231
+ console.error(error);
232
+ }
233
+ }
234
+ return undefined;
235
+ };
236
+
237
+ export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => {
238
+ const errors: Record<number, string> = {
239
+ 400: 'Bad Request',
240
+ 401: 'Unauthorized',
241
+ 402: 'Payment Required',
242
+ 403: 'Forbidden',
243
+ 404: 'Not Found',
244
+ 405: 'Method Not Allowed',
245
+ 406: 'Not Acceptable',
246
+ 407: 'Proxy Authentication Required',
247
+ 408: 'Request Timeout',
248
+ 409: 'Conflict',
249
+ 410: 'Gone',
250
+ 411: 'Length Required',
251
+ 412: 'Precondition Failed',
252
+ 413: 'Payload Too Large',
253
+ 414: 'URI Too Long',
254
+ 415: 'Unsupported Media Type',
255
+ 416: 'Range Not Satisfiable',
256
+ 417: 'Expectation Failed',
257
+ 418: 'Im a teapot',
258
+ 421: 'Misdirected Request',
259
+ 422: 'Unprocessable Content',
260
+ 423: 'Locked',
261
+ 424: 'Failed Dependency',
262
+ 425: 'Too Early',
263
+ 426: 'Upgrade Required',
264
+ 428: 'Precondition Required',
265
+ 429: 'Too Many Requests',
266
+ 431: 'Request Header Fields Too Large',
267
+ 451: 'Unavailable For Legal Reasons',
268
+ 500: 'Internal Server Error',
269
+ 501: 'Not Implemented',
270
+ 502: 'Bad Gateway',
271
+ 503: 'Service Unavailable',
272
+ 504: 'Gateway Timeout',
273
+ 505: 'HTTP Version Not Supported',
274
+ 506: 'Variant Also Negotiates',
275
+ 507: 'Insufficient Storage',
276
+ 508: 'Loop Detected',
277
+ 510: 'Not Extended',
278
+ 511: 'Network Authentication Required',
279
+ ...options.errors,
280
+ }
281
+
282
+ const error = errors[result.status];
283
+ if (error) {
284
+ throw new ApiError(options, result, error);
285
+ }
286
+
287
+ if (!result.ok) {
288
+ const errorStatus = result.status ?? 'unknown';
289
+ const errorStatusText = result.statusText ?? 'unknown';
290
+ const errorBody = (() => {
291
+ try {
292
+ return JSON.stringify(result.body, null, 2);
293
+ } catch (e) {
294
+ return undefined;
295
+ }
296
+ })();
297
+
298
+ throw new ApiError(options, result,
299
+ `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
300
+ );
301
+ }
302
+ };
303
+
304
+ /**
305
+ * Request method
306
+ * @param config The OpenAPI configuration object
307
+ * @param options The request options from the service
308
+ * @returns CancelablePromise<T>
309
+ * @throws ApiError
310
+ */
311
+ export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions<T>): CancelablePromise<T> => {
312
+ return new CancelablePromise(async (resolve, reject, onCancel) => {
313
+ try {
314
+ const url = getUrl(config, options);
315
+ const formData = getFormData(options);
316
+ const body = getRequestBody(options);
317
+ const headers = await getHeaders(config, options);
318
+
319
+ if (!onCancel.isCancelled) {
320
+ let response = await sendRequest(config, options, url, body, formData, headers, onCancel);
321
+
322
+ for (const fn of config.interceptors.response._fns) {
323
+ response = await fn(response);
324
+ }
325
+
326
+ const responseBody = await getResponseBody(response);
327
+ const responseHeader = getResponseHeader(response, options.responseHeader);
328
+
329
+ let transformedBody = responseBody;
330
+ if (options.responseTransformer && response.ok) {
331
+ transformedBody = await options.responseTransformer(responseBody)
332
+ }
333
+
334
+ const result: ApiResult = {
335
+ url,
336
+ ok: response.ok,
337
+ status: response.status,
338
+ statusText: response.statusText,
339
+ body: responseHeader ?? transformedBody,
340
+ };
341
+
342
+ catchErrorCodes(options, result);
343
+
344
+ resolve(result.body);
345
+ }
346
+ } catch (error) {
347
+ reject(error);
348
+ }
349
+ });
350
+ };
@@ -0,0 +1,6 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export { ApiError } from './core/ApiError';
3
+ export { CancelablePromise, CancelError } from './core/CancelablePromise';
4
+ export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI';
5
+ export * from './sdk.gen';
6
+ export * from './types.gen';