(options: HttpOptions, extra: RequestInit = {})
| 352 | * @param extra Any extra RequestInit values |
| 353 | */ |
| 354 | export const buildRequestInit = (options: HttpOptions, extra: RequestInit = {}): RequestInit => { |
| 355 | const output: RequestInit = { |
| 356 | method: options.method || 'GET', |
| 357 | headers: options.headers, |
| 358 | ...extra, |
| 359 | }; |
| 360 | |
| 361 | // Get the content-type |
| 362 | const headers = normalizeHttpHeaders(options.headers); |
| 363 | const type = headers['content-type'] || ''; |
| 364 | |
| 365 | // If body is already a string, then pass it through as-is. |
| 366 | if (typeof options.data === 'string') { |
| 367 | output.body = options.data; |
| 368 | } |
| 369 | // Build request initializers based off of content-type |
| 370 | else if (type.includes('application/x-www-form-urlencoded')) { |
| 371 | const params = new URLSearchParams(); |
| 372 | for (const [key, value] of Object.entries(options.data || {})) { |
| 373 | params.set(key, value as any); |
| 374 | } |
| 375 | output.body = params.toString(); |
| 376 | } else if (type.includes('multipart/form-data') || options.data instanceof FormData) { |
| 377 | const form = new FormData(); |
| 378 | if (options.data instanceof FormData) { |
| 379 | options.data.forEach((value, key) => { |
| 380 | form.append(key, value); |
| 381 | }); |
| 382 | } else { |
| 383 | for (const key of Object.keys(options.data)) { |
| 384 | form.append(key, options.data[key]); |
| 385 | } |
| 386 | } |
| 387 | output.body = form; |
| 388 | const headers = new Headers(output.headers); |
| 389 | headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary |
| 390 | output.headers = headers; |
| 391 | } else if (type.includes('application/json') || typeof options.data === 'object') { |
| 392 | output.body = JSON.stringify(options.data); |
| 393 | } |
| 394 | |
| 395 | return output; |
| 396 | }; |
| 397 | |
| 398 | // WEB IMPLEMENTATION |
| 399 | export class CapacitorHttpPluginWeb extends WebPlugin implements CapacitorHttpPlugin { |
no test coverage detected