No Description

index.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @author wkh237
  3. * @version 0.3.3
  4. */
  5. import { NativeModules } from 'react-native'
  6. import base64 from 'base-64'
  7. const RNFetchBlob = NativeModules.RNFetchBlob
  8. // Show warning if native module not detected
  9. if(RNFetchBlob === void 0) {
  10. console.warn(
  11. 'react-native-fetch-blob could not find native module.',
  12. 'please make sure you have linked native modules using `rnpm link`,',
  13. 'and restart RN packager or manually compile IOS/Android project.'
  14. )
  15. }
  16. // Promise wrapper function
  17. const fetch = (...args) => {
  18. let promise = new Promise((resolve, reject) => {
  19. let [method, url, headers, body] = [...args]
  20. let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'
  21. RNFetchBlob[nativeMethodName](method, url, headers || {}, body, (err, ...data) => {
  22. if(err)
  23. reject(new Error(err, ...data))
  24. else
  25. resolve(new FetchBlobResponse(...data))
  26. })
  27. })
  28. return promise
  29. }
  30. /**
  31. * RNFetchBlob response object class.
  32. */
  33. class FetchBlobResponse {
  34. constructor(data) {
  35. this.data = data
  36. /**
  37. * Convert result to javascript Blob object.
  38. * @param {string} contentType MIME type of the blob object.
  39. * @param {number} sliceSize Slice size.
  40. * @return {blob} Return Blob object.
  41. */
  42. this.blob = (contentType, sliceSize) => {
  43. console.warn('FetchBlobResponse.blob() is deprecated and has no funtionality.')
  44. return null
  45. }
  46. /**
  47. * Convert result to text.
  48. * @return {string} Decoded base64 string.
  49. */
  50. this.text = () => {
  51. return base64.decode(this.data)
  52. }
  53. /**
  54. * Convert result to JSON object.
  55. * @return {object} Parsed javascript object.
  56. */
  57. this.json = () => {
  58. return JSON.parse(base64.decode(this.data))
  59. }
  60. /**
  61. * Return BASE64 string directly.
  62. * @return {string} BASE64 string of response body.
  63. */
  64. this.base64 = () => {
  65. return this.data
  66. }
  67. }
  68. }
  69. export default {
  70. fetch, FetchBlobResponse, base64
  71. }