| 397 | |
| 398 | // WEB IMPLEMENTATION |
| 399 | export class CapacitorHttpPluginWeb extends WebPlugin implements CapacitorHttpPlugin { |
| 400 | /** |
| 401 | * Perform an Http request given a set of options |
| 402 | * @param options Options to build the HTTP request |
| 403 | */ |
| 404 | async request(options: HttpOptions): Promise<HttpResponse> { |
| 405 | const requestInit = buildRequestInit(options, options.webFetchExtra); |
| 406 | const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); |
| 407 | const url = urlParams ? `${options.url}?${urlParams}` : options.url; |
| 408 | |
| 409 | const response = await fetch(url, requestInit); |
| 410 | const contentType = response.headers.get('content-type') || ''; |
| 411 | |
| 412 | // Default to 'text' responseType so no parsing happens |
| 413 | let { responseType = 'text' } = response.ok ? options : {}; |
| 414 | |
| 415 | // If the response content-type is json, force the response to be json |
| 416 | if (contentType.includes('application/json')) { |
| 417 | responseType = 'json'; |
| 418 | } |
| 419 | |
| 420 | let data: any; |
| 421 | let blob: any; |
| 422 | switch (responseType) { |
| 423 | case 'arraybuffer': |
| 424 | case 'blob': |
| 425 | blob = await response.blob(); |
| 426 | data = await readBlobAsBase64(blob); |
| 427 | break; |
| 428 | case 'json': |
| 429 | data = await response.json(); |
| 430 | break; |
| 431 | case 'document': |
| 432 | case 'text': |
| 433 | default: |
| 434 | data = await response.text(); |
| 435 | } |
| 436 | |
| 437 | // Convert fetch headers to Capacitor HttpHeaders |
| 438 | const headers = {} as HttpHeaders; |
| 439 | response.headers.forEach((value: string, key: string) => { |
| 440 | headers[key] = value; |
| 441 | }); |
| 442 | |
| 443 | return { |
| 444 | data, |
| 445 | headers, |
| 446 | status: response.status, |
| 447 | url: response.url, |
| 448 | }; |
| 449 | } |
| 450 | |
| 451 | /** |
| 452 | * Perform an Http GET request given a set of options |
| 453 | * @param options Options to build the HTTP request |
| 454 | */ |
| 455 | async get(options: HttpOptions): Promise<HttpResponse> { |
| 456 | return this.request({ ...options, method: 'GET' }); |
nothing calls this directly
no outgoing calls
no test coverage detected