Projekt

Obecné

Profil

Stáhnout (7.09 KB) Statistiky
| Větev: | Tag: | Revize:
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
export type QueryParamsType = Record<string | number, any>;
13
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
14

    
15
export interface FullRequestParams extends Omit<RequestInit, "body"> {
16
  /** set parameter to `true` for call `securityWorker` for this request */
17
  secure?: boolean;
18
  /** request path */
19
  path: string;
20
  /** content type of request body */
21
  type?: ContentType;
22
  /** query params */
23
  query?: QueryParamsType;
24
  /** format of response (i.e. response.json() -> format: "json") */
25
  format?: ResponseFormat;
26
  /** request body */
27
  body?: unknown;
28
  /** base url */
29
  baseUrl?: string;
30
  /** request cancellation token */
31
  cancelToken?: CancelToken;
32
}
33

    
34
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
35

    
36
export interface ApiConfig<SecurityDataType = unknown> {
37
  baseUrl?: string;
38
  baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
39
  securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
40
  customFetch?: typeof fetch;
41
}
42

    
43
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
44
  data: D;
45
  error: E;
46
}
47

    
48
type CancelToken = Symbol | string | number;
49

    
50
export enum ContentType {
51
  Json = "application/json",
52
  FormData = "multipart/form-data",
53
  UrlEncoded = "application/x-www-form-urlencoded",
54
}
55

    
56
export class HttpClient<SecurityDataType = unknown> {
57
  public baseUrl: string = "http://localhost:8080";
58
  private securityData: SecurityDataType | null = null;
59
  private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
60
  private abortControllers = new Map<CancelToken, AbortController>();
61
  private customFetch = (...fetchParams: Parameters<typeof fetch>) => fetch(...fetchParams);
62

    
63
  private baseApiParams: RequestParams = {
64
    credentials: "same-origin",
65
    headers: {},
66
    redirect: "follow",
67
    referrerPolicy: "no-referrer",
68
  };
69

    
70
  constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
71
    Object.assign(this, apiConfig);
72
  }
73

    
74
  public setSecurityData = (data: SecurityDataType | null) => {
75
    this.securityData = data;
76
  };
77

    
78
  private encodeQueryParam(key: string, value: any) {
79
    const encodedKey = encodeURIComponent(key);
80
    return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
81
  }
82

    
83
  private addQueryParam(query: QueryParamsType, key: string) {
84
    return this.encodeQueryParam(key, query[key]);
85
  }
86

    
87
  private addArrayQueryParam(query: QueryParamsType, key: string) {
88
    const value = query[key];
89
    return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");
90
  }
91

    
92
  protected toQueryString(rawQuery?: QueryParamsType): string {
93
    const query = rawQuery || {};
94
    const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
95
    return keys
96
      .map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key)))
97
      .join("&");
98
  }
99

    
100
  protected addQueryParams(rawQuery?: QueryParamsType): string {
101
    const queryString = this.toQueryString(rawQuery);
102
    return queryString ? `?${queryString}` : "";
103
  }
104

    
105
  private contentFormatters: Record<ContentType, (input: any) => any> = {
106
    [ContentType.Json]: (input: any) =>
107
      input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
108
    [ContentType.FormData]: (input: any) =>
109
      Object.keys(input || {}).reduce((formData, key) => {
110
        const property = input[key];
111
        formData.append(
112
          key,
113
          property instanceof Blob
114
            ? property
115
            : typeof property === "object" && property !== null
116
            ? JSON.stringify(property)
117
            : `${property}`,
118
        );
119
        return formData;
120
      }, new FormData()),
121
    [ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
122
  };
123

    
124
  private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
125
    return {
126
      ...this.baseApiParams,
127
      ...params1,
128
      ...(params2 || {}),
129
      headers: {
130
        ...(this.baseApiParams.headers || {}),
131
        ...(params1.headers || {}),
132
        ...((params2 && params2.headers) || {}),
133
      },
134
    };
135
  }
136

    
137
  private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
138
    if (this.abortControllers.has(cancelToken)) {
139
      const abortController = this.abortControllers.get(cancelToken);
140
      if (abortController) {
141
        return abortController.signal;
142
      }
143
      return void 0;
144
    }
145

    
146
    const abortController = new AbortController();
147
    this.abortControllers.set(cancelToken, abortController);
148
    return abortController.signal;
149
  };
150

    
151
  public abortRequest = (cancelToken: CancelToken) => {
152
    const abortController = this.abortControllers.get(cancelToken);
153

    
154
    if (abortController) {
155
      abortController.abort();
156
      this.abortControllers.delete(cancelToken);
157
    }
158
  };
159

    
160
  public request = async <T = any, E = any>({
161
    body,
162
    secure,
163
    path,
164
    type,
165
    query,
166
    format,
167
    baseUrl,
168
    cancelToken,
169
    ...params
170
  }: FullRequestParams): Promise<HttpResponse<T, E>> => {
171
    const secureParams =
172
      ((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
173
        this.securityWorker &&
174
        (await this.securityWorker(this.securityData))) ||
175
      {};
176
    const requestParams = this.mergeRequestParams(params, secureParams);
177
    const queryString = query && this.toQueryString(query);
178
    const payloadFormatter = this.contentFormatters[type || ContentType.Json];
179
    const responseFormat = format || requestParams.format;
180

    
181
    return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
182
      ...requestParams,
183
      headers: {
184
        ...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
185
        ...(requestParams.headers || {}),
186
      },
187
      signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
188
      body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
189
    }).then(async (response) => {
190
      const r = response as HttpResponse<T, E>;
191
      r.data = null as unknown as T;
192
      r.error = null as unknown as E;
193

    
194
      const data = !responseFormat
195
        ? r
196
        : await response[responseFormat]()
197
            .then((data) => {
198
              if (r.ok) {
199
                r.data = data;
200
              } else {
201
                r.error = data;
202
              }
203
              return r;
204
            })
205
            .catch((e) => {
206
              r.error = e;
207
              return r;
208
            });
209

    
210
      if (cancelToken) {
211
        this.abortControllers.delete(cancelToken);
212
      }
213

    
214
      if (!response.ok) throw data;
215
      return data;
216
    });
217
  };
218
}
(8-8/8)