github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/typescript-fetch/runtime.mustache (about) 1 /* tslint:disable */ 2 /* eslint-disable */ 3 {{>licenseInfo}} 4 5 export const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ""); 6 7 const isBlob = (value: any) => typeof Blob !== 'undefined' && value instanceof Blob; 8 9 /** 10 * This is the base class for all generated API classes. 11 */ 12 export class BaseAPI { 13 14 private middleware: Middleware[]; 15 16 constructor(protected configuration = new Configuration()) { 17 this.middleware = configuration.middleware; 18 } 19 20 withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) { 21 const next = this.clone<T>(); 22 next.middleware = next.middleware.concat(...middlewares); 23 return next; 24 } 25 26 withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) { 27 const middlewares = preMiddlewares.map((pre) => ({ pre })); 28 return this.withMiddleware<T>(...middlewares); 29 } 30 31 withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) { 32 const middlewares = postMiddlewares.map((post) => ({ post })); 33 return this.withMiddleware<T>(...middlewares); 34 } 35 36 protected async request(context: RequestOpts): Promise<Response> { 37 const { url, init } = this.createFetchParams(context); 38 const response = await this.fetchApi(url, init); 39 if (response.status >= 200 && response.status < 300) { 40 return response; 41 } 42 throw response; 43 } 44 45 private createFetchParams(context: RequestOpts) { 46 let url = this.configuration.basePath + context.path; 47 if (context.query !== undefined && Object.keys(context.query).length !== 0) { 48 // only add the querystring to the URL if there are query parameters. 49 // this is done to avoid urls ending with a "?" character which buggy webservers 50 // do not handle correctly sometimes. 51 url += '?' + this.configuration.queryParamsStringify(context.query); 52 } 53 const body = (context.body instanceof FormData || context.body instanceof URLSearchParams || isBlob(context.body)) 54 ? context.body 55 : JSON.stringify(context.body); 56 57 const headers = Object.assign({}, this.configuration.headers, context.headers); 58 const init = { 59 method: context.method, 60 headers: headers, 61 body, 62 credentials: this.configuration.credentials 63 }; 64 return { url, init }; 65 } 66 67 private fetchApi = async (url: string, init: RequestInit) => { 68 let fetchParams = { url, init }; 69 for (const middleware of this.middleware) { 70 if (middleware.pre) { 71 fetchParams = await middleware.pre({ 72 fetch: this.fetchApi, 73 ...fetchParams, 74 }) || fetchParams; 75 } 76 } 77 let response = await this.configuration.fetchApi(fetchParams.url, fetchParams.init); 78 for (const middleware of this.middleware) { 79 if (middleware.post) { 80 response = await middleware.post({ 81 fetch: this.fetchApi, 82 url, 83 init, 84 response: response.clone(), 85 }) || response; 86 } 87 } 88 return response; 89 } 90 91 /** 92 * Create a shallow clone of `this` by constructing a new instance 93 * and then shallow cloning data members. 94 */ 95 private clone<T extends BaseAPI>(this: T): T { 96 const constructor = this.constructor as any; 97 const next = new constructor(this.configuration); 98 next.middleware = this.middleware.slice(); 99 return next; 100 } 101 102 protected flattenDeepParams(obj: any, prefix?: string): any[] { 103 var res: any[] = []; 104 if (obj?.constructor === Array) { 105 obj.forEach(value => { 106 res = res.concat(this.flattenDeepParams(value, `${prefix}[]`)); 107 }); 108 } else if (obj?.constructor === Object) { 109 for (const key in obj) { 110 res = res.concat(this.flattenDeepParams(obj[key], prefix ? `${prefix}[${key}]` : key)); 111 } 112 } else { 113 res = [[prefix, obj]]; 114 } 115 return res; 116 } 117 }; 118 119 export class RequiredError extends Error { 120 name: "RequiredError" = "RequiredError"; 121 constructor(public field: string, msg?: string) { 122 super(msg); 123 } 124 } 125 126 export const COLLECTION_FORMATS = { 127 csv: ",", 128 ssv: " ", 129 tsv: "\t", 130 pipes: "|", 131 }; 132 133 export type FetchAPI = {{#typescriptThreePlus}}WindowOrWorkerGlobalScope{{/typescriptThreePlus}}{{^typescriptThreePlus}}GlobalFetch{{/typescriptThreePlus}}['fetch']; 134 135 export interface ConfigurationParameters { 136 basePath?: string; // override base path 137 fetchApi?: FetchAPI; // override for fetch implementation 138 middleware?: Middleware[]; // middleware to apply before/after fetch requests 139 queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings 140 username?: string; // parameter for basic security 141 password?: string; // parameter for basic security 142 apiKey?: string | ((name: string) => string); // parameter for apiKey security 143 accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security 144 headers?: HTTPHeaders; //header params we want to use on every request 145 credentials?: RequestCredentials; //value for the credentials param we want to use on each request 146 } 147 148 export class Configuration { 149 constructor(private configuration: ConfigurationParameters = {}) { 150 if (configuration.headers === undefined) { 151 configuration.headers = {} 152 } 153 154 configuration.headers["User-Agent"] = "OpenAPI-Generator/{{npmVersion}}/js" 155 } 156 157 get basePath(): string { 158 return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; 159 } 160 161 get fetchApi(): FetchAPI { 162 return this.configuration.fetchApi || window.fetch.bind(window); 163 } 164 165 get middleware(): Middleware[] { 166 return this.configuration.middleware || []; 167 } 168 169 get queryParamsStringify(): (params: HTTPQuery) => string { 170 return this.configuration.queryParamsStringify || querystring; 171 } 172 173 get username(): string | undefined { 174 return this.configuration.username; 175 } 176 177 get password(): string | undefined { 178 return this.configuration.password; 179 } 180 181 get apiKey(): ((name: string) => string) | undefined { 182 const apiKey = this.configuration.apiKey; 183 if (apiKey) { 184 return typeof apiKey === 'function' ? apiKey : () => apiKey; 185 } 186 return undefined; 187 } 188 189 get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { 190 const accessToken = this.configuration.accessToken; 191 if (accessToken) { 192 return typeof accessToken === 'function' ? accessToken : () => accessToken; 193 } 194 return undefined; 195 } 196 197 get headers(): HTTPHeaders | undefined { 198 return this.configuration.headers; 199 } 200 201 get credentials(): RequestCredentials | undefined { 202 return this.configuration.credentials; 203 } 204 } 205 206 export type Json = any; 207 export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; 208 export type HTTPHeaders = { [key: string]: string }; 209 export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | HTTPQuery }; 210 export type HTTPBody = Json | FormData | URLSearchParams; 211 export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; 212 213 export interface FetchParams { 214 url: string; 215 init: RequestInit; 216 } 217 218 export interface RequestOpts { 219 path: string; 220 method: HTTPMethod; 221 headers: HTTPHeaders; 222 query?: HTTPQuery; 223 body?: HTTPBody; 224 } 225 226 export function exists(json: any, key: string) { 227 const value = json[key]; 228 return value !== null && value !== undefined; 229 } 230 231 export function querystring(params: HTTPQuery, prefix: string = ''): string { 232 return Object.keys(params) 233 .map((key) => { 234 const fullKey = prefix + (prefix.length ? `[${key}]` : key); 235 const value = params[key]; 236 if (value instanceof Array) { 237 const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) 238 .join(`&${encodeURIComponent(fullKey)}=`); 239 return `${encodeURIComponent(fullKey)}=${multiValue}`; 240 } 241 if (value instanceof Object) { 242 return querystring(value as HTTPQuery, fullKey); 243 } 244 return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; 245 }) 246 .filter(part => part.length > 0) 247 .join('&'); 248 } 249 250 export function mapValues(data: any, fn: (item: any) => any) { 251 return Object.keys(data).reduce( 252 (acc, key) => ({ ...acc, [key]: fn(data[key]) }), 253 {} 254 ); 255 } 256 257 export function canConsumeForm(consumes: Consume[]): boolean { 258 for (const consume of consumes) { 259 if ('multipart/form-data' === consume.contentType) { 260 return true; 261 } 262 } 263 return false; 264 } 265 266 export interface Consume { 267 contentType: string 268 } 269 270 export interface RequestContext { 271 fetch: FetchAPI; 272 url: string; 273 init: RequestInit; 274 } 275 276 export interface ResponseContext { 277 fetch: FetchAPI; 278 url: string; 279 init: RequestInit; 280 response: Response; 281 } 282 283 export interface Middleware { 284 pre?(context: RequestContext): Promise<FetchParams | void>; 285 post?(context: ResponseContext): Promise<Response | void>; 286 } 287 288 export interface ApiResponse<T> { 289 raw: Response; 290 value(): Promise<T>; 291 } 292 293 export interface ResponseTransformer<T> { 294 (json: any): T; 295 } 296 297 export class JSONApiResponse<T> { 298 constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) {} 299 300 async value(): Promise<T> { 301 return this.transformer(await this.raw.json()); 302 } 303 } 304 305 export class VoidApiResponse { 306 constructor(public raw: Response) {} 307 308 async value(): Promise<void> { 309 return undefined; 310 } 311 } 312 313 export class BlobApiResponse { 314 constructor(public raw: Response) {} 315 316 async value(): Promise<Blob> { 317 return await this.raw.blob(); 318 }; 319 } 320 321 export class TextApiResponse { 322 constructor(public raw: Response) {} 323 324 async value(): Promise<string> { 325 return await this.raw.text(); 326 }; 327 }