RCTNetworking.android.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. // Do not require the native RCTNetworking module directly! Use this wrapper module instead.
  12. // It will add the necessary requestId, so that you don't have to generate it yourself.
  13. const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter');
  14. const convertRequestBody = require('./convertRequestBody');
  15. import NativeNetworkingAndroid from './NativeNetworkingAndroid';
  16. import type {RequestBody} from './convertRequestBody';
  17. type Header = [string, string];
  18. // Convert FormData headers to arrays, which are easier to consume in
  19. // native on Android.
  20. function convertHeadersMapToArray(headers: Object): Array<Header> {
  21. const headerArray = [];
  22. for (const name in headers) {
  23. headerArray.push([name, headers[name]]);
  24. }
  25. return headerArray;
  26. }
  27. let _requestId = 1;
  28. function generateRequestId(): number {
  29. return _requestId++;
  30. }
  31. /**
  32. * This class is a wrapper around the native RCTNetworking module. It adds a necessary unique
  33. * requestId to each network request that can be used to abort that request later on.
  34. */
  35. class RCTNetworking extends NativeEventEmitter {
  36. constructor() {
  37. super(NativeNetworkingAndroid);
  38. }
  39. sendRequest(
  40. method: string,
  41. trackingName: string,
  42. url: string,
  43. headers: Object,
  44. data: RequestBody,
  45. responseType: 'text' | 'base64',
  46. incrementalUpdates: boolean,
  47. timeout: number,
  48. callback: (requestId: number) => mixed,
  49. withCredentials: boolean,
  50. ) {
  51. const body = convertRequestBody(data);
  52. if (body && body.formData) {
  53. body.formData = body.formData.map(part => ({
  54. ...part,
  55. headers: convertHeadersMapToArray(part.headers),
  56. }));
  57. }
  58. const requestId = generateRequestId();
  59. NativeNetworkingAndroid.sendRequest(
  60. method,
  61. url,
  62. requestId,
  63. convertHeadersMapToArray(headers),
  64. {...body, trackingName},
  65. responseType,
  66. incrementalUpdates,
  67. timeout,
  68. withCredentials,
  69. );
  70. callback(requestId);
  71. }
  72. abortRequest(requestId: number) {
  73. NativeNetworkingAndroid.abortRequest(requestId);
  74. }
  75. clearCookies(callback: (result: boolean) => any) {
  76. NativeNetworkingAndroid.clearCookies(callback);
  77. }
  78. }
  79. module.exports = (new RCTNetworking(): RCTNetworking);