Няма описание

XMLHttpRequest.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. import RNFetchBlob from '../index.js'
  5. import XMLHttpRequestEventTarget from './XMLHttpRequestEventTarget.js'
  6. import Log from '../utils/log.js'
  7. import Blob from './Blob.js'
  8. import ProgressEvent from './ProgressEvent.js'
  9. const log = new Log('XMLHttpRequest')
  10. log.level(0)
  11. const UNSENT = 0
  12. const OPENED = 1
  13. const HEADERS_RECEIVED = 2
  14. const LOADING = 3
  15. const DONE = 4
  16. export default class XMLHttpRequest extends XMLHttpRequestEventTarget{
  17. _onreadystatechange : () => void;
  18. upload : XMLHttpRequestEventTarget = new XMLHttpRequestEventTarget();
  19. static binaryContentTypes : Array<string> = [
  20. 'image/', 'video/', 'audio/'
  21. ];
  22. // readonly
  23. _readyState : number = UNSENT;
  24. _response : any = '';
  25. _responseText : any = null;
  26. _responseHeaders : any = {};
  27. _responseType : '' | 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' = '';
  28. // TODO : not suppoted ATM
  29. _responseURL : null = '';
  30. _responseXML : null = '';
  31. _status : number = 0;
  32. _statusText : string = '';
  33. _timeout : number = 0;
  34. _sendFlag : boolean = false;
  35. _uploadStarted : boolean = false;
  36. // RNFetchBlob compatible data structure
  37. _config : RNFetchBlobConfig = {};
  38. _url : any;
  39. _method : string;
  40. _headers: any = {
  41. 'Content-Type' : 'text/plain'
  42. };
  43. _body: any;
  44. // RNFetchBlob promise object, which has `progress`, `uploadProgress`, and
  45. // `cancel` methods.
  46. _task: any;
  47. // constants
  48. get UNSENT() { return UNSENT }
  49. get OPENED() { return OPENED }
  50. get HEADERS_RECEIVED() { return HEADERS_RECEIVED }
  51. get LOADING() { return LOADING }
  52. get DONE() { return DONE }
  53. static get UNSENT() {
  54. return UNSENT
  55. }
  56. static get OPENED() {
  57. return OPENED
  58. }
  59. static get HEADERS_RECEIVED() {
  60. return HEADERS_RECEIVED
  61. }
  62. static get LOADING() {
  63. return LOADING
  64. }
  65. static get DONE() {
  66. return DONE
  67. }
  68. static addBinaryContentType(substr:string) {
  69. for(let i in XMLHttpRequest.binaryContentTypes) {
  70. if(new RegExp(substr,'i').test(XMLHttpRequest.binaryContentTypes[i])) {
  71. return
  72. }
  73. }
  74. XMLHttpRequest.binaryContentTypes.push(substr)
  75. }
  76. static removeBinaryContentType(val) {
  77. for(let i in XMLHttpRequest.binaryContentTypes) {
  78. if(new RegExp(substr,'i').test(XMLHttpRequest.binaryContentTypes[i])) {
  79. XMLHttpRequest.binaryContentTypes.splice(i,1)
  80. return
  81. }
  82. }
  83. }
  84. constructor() {
  85. super()
  86. log.verbose('XMLHttpRequest constructor called')
  87. }
  88. /**
  89. * XMLHttpRequest.open, always async, user and password not supported. When
  90. * this method invoked, headers should becomes empty again.
  91. * @param {string} method Request method
  92. * @param {string} url Request URL
  93. * @param {true} async Always async
  94. * @param {any} user NOT SUPPORTED
  95. * @param {any} password NOT SUPPORTED
  96. */
  97. open(method:string, url:string, async:true, user:any, password:any) {
  98. log.verbose('XMLHttpRequest open ', method, url, async, user, password)
  99. this._method = method
  100. this._url = url
  101. this._headers = {}
  102. this._dispatchReadStateChange(XMLHttpRequest.OPENED)
  103. }
  104. /**
  105. * Invoke this function to send HTTP request, and set body.
  106. * @param {any} body Body in RNfetchblob flavor
  107. */
  108. send(body) {
  109. if(this._readyState !== XMLHttpRequest.OPENED)
  110. throw 'InvalidStateError : XMLHttpRequest is not opened yet.'
  111. this._sendFlag = true
  112. log.verbose('XMLHttpRequest send ', body)
  113. let {_method, _url, _headers } = this
  114. log.verbose('sending request with args', _method, _url, _headers, body)
  115. log.verbose(typeof body, body instanceof FormData)
  116. if(body instanceof Blob) {
  117. body = RNFetchBlob.wrap(body.getRNFetchBlobRef())
  118. }
  119. else if(typeof body === 'object') {
  120. body = JSON.stringify(body)
  121. }
  122. else
  123. body = body ? body.toString() : body
  124. this._task = RNFetchBlob
  125. .config({
  126. auto: true,
  127. timeout : this._timeout,
  128. binaryContentTypes : XMLHttpRequest.binaryContentTypes
  129. })
  130. .fetch(_method, _url, _headers, body)
  131. this._task
  132. .stateChange(this._headerReceived.bind(this))
  133. .uploadProgress(this._uploadProgressEvent.bind(this))
  134. .progress(this._progressEvent.bind(this))
  135. .catch(this._onError.bind(this))
  136. .then(this._onDone.bind(this))
  137. }
  138. overrideMimeType(mime:string) {
  139. log.verbose('XMLHttpRequest overrideMimeType', mime)
  140. this._headers['Content-Type'] = mime
  141. }
  142. setRequestHeader(name, value) {
  143. log.verbose('XMLHttpRequest set header', name, value)
  144. if(this._readyState !== OPENED || this._sendFlag) {
  145. throw `InvalidStateError : Calling setRequestHeader in wrong state ${this._readyState}`
  146. }
  147. // UNICODE SHOULD NOT PASS
  148. if(typeof name !== 'string' || /[^\u0000-\u00ff]/.test(name)) {
  149. throw 'TypeError : header field name should be a string'
  150. }
  151. //
  152. let invalidPatterns = [
  153. /[\(\)\>\<\@\,\:\\\/\[\]\?\=\}\{\s\ \u007f\;\t\0\v\r]/,
  154. /tt/
  155. ]
  156. for(let i in invalidPatterns) {
  157. if(invalidPatterns[i].test(name) || typeof name !== 'string') {
  158. throw `SyntaxError : Invalid header field name ${name}`
  159. }
  160. }
  161. this._headers[name] = value
  162. }
  163. abort() {
  164. log.verbose('XMLHttpRequest abort ')
  165. if(!this._task)
  166. return
  167. this._task.cancel((err) => {
  168. let e = {
  169. timeStamp : Date.now(),
  170. }
  171. if(this.onabort)
  172. this.onabort()
  173. if(err) {
  174. e.detail = err
  175. e.type = 'error'
  176. this.dispatchEvent('error', e)
  177. }
  178. else {
  179. e.type = 'abort'
  180. this.dispatchEvent('abort', e)
  181. }
  182. })
  183. }
  184. getResponseHeader(field:string):string | null {
  185. log.verbose('XMLHttpRequest get header', field)
  186. if(!this._responseHeaders)
  187. return null
  188. return this.responseHeaders[field] || null
  189. }
  190. getAllResponseHeaders():string | null {
  191. log.verbose('XMLHttpRequest get all headers', this._responseHeaders)
  192. if(!this._responseHeaders)
  193. return ''
  194. let result = ''
  195. let respHeaders = this.responseHeaders
  196. for(let i in respHeaders) {
  197. result += `${i}:${respHeaders[i]}\r\n`
  198. }
  199. return result
  200. }
  201. _headerReceived(e) {
  202. log.verbose('header received ', this._task.taskId, e)
  203. this.responseURL = this._url
  204. if(e.state === "2") {
  205. this._responseHeaders = e.headers
  206. this._statusText = e.status
  207. this._responseType = e.respType || ''
  208. this._status = Math.floor(e.status)
  209. this._dispatchReadStateChange(XMLHttpRequest.HEADERS_RECEIVED)
  210. }
  211. }
  212. _uploadProgressEvent(send:number, total:number) {
  213. if(!this._uploadStarted) {
  214. this.upload.dispatchEvent('loadstart')
  215. this._uploadStarted = true
  216. }
  217. if(send >= total)
  218. this.upload.dispatchEvent('load')
  219. this.upload.dispatchEvent('progress', new ProgressEvent(true, send, total))
  220. }
  221. _progressEvent(send:number, total:number) {
  222. log.verbose(this.readyState)
  223. if(this._readyState === XMLHttpRequest.HEADERS_RECEIVED)
  224. this._dispatchReadStateChange(XMLHttpRequest.LOADING)
  225. let lengthComputable = false
  226. if(total && total >= 0)
  227. lengthComputable = true
  228. let e = new ProgressEvent(lengthComputable, send, total)
  229. this.dispatchEvent('progress', e)
  230. }
  231. _onError(err) {
  232. let statusCode = Math.floor(this.status)
  233. if(statusCode >= 100 && statusCode !== 408) {
  234. return
  235. }
  236. log.verbose('XMLHttpRequest error', err)
  237. this._statusText = err
  238. this._status = String(err).match(/\d+/)
  239. this._status = this._status ? Math.floor(this.status) : 404
  240. this._dispatchReadStateChange(XMLHttpRequest.DONE)
  241. if(err && String(err.message).match(/(timed\sout|timedout)/) || this._status == 408) {
  242. this.dispatchEvent('timeout')
  243. }
  244. this.dispatchEvent('loadend')
  245. this.dispatchEvent('error', {
  246. type : 'error',
  247. detail : err
  248. })
  249. this.clearEventListeners()
  250. }
  251. _onDone(resp) {
  252. log.verbose('XMLHttpRequest done', this._url, resp)
  253. this._statusText = this._status
  254. if(resp) {
  255. switch(resp.type) {
  256. case 'base64' :
  257. if(this._responseType === 'json') {
  258. this._responseText = resp.text()
  259. this._response = resp.json()
  260. }
  261. else {
  262. this._responseText = resp.text()
  263. this._response = this.responseText
  264. }
  265. break;
  266. case 'path' :
  267. this.response = resp.blob()
  268. break;
  269. default :
  270. this._responseText = resp.text()
  271. this._response = this.responseText
  272. break;
  273. }
  274. this.dispatchEvent('load')
  275. this.dispatchEvent('loadend')
  276. this._dispatchReadStateChange(XMLHttpRequest.DONE)
  277. }
  278. this.clearEventListeners()
  279. }
  280. _dispatchReadStateChange(state) {
  281. this._readyState = state
  282. if(typeof this._onreadystatechange === 'function')
  283. this._onreadystatechange()
  284. }
  285. set onreadystatechange(fn:() => void) {
  286. log.verbose('XMLHttpRequest set onreadystatechange', fn.toString())
  287. this._onreadystatechange = fn
  288. }
  289. get onreadystatechange() {
  290. return this._onreadystatechange
  291. }
  292. get readyState() {
  293. log.verbose('get readyState', this._readyState)
  294. return this._readyState
  295. }
  296. get status() {
  297. log.verbose('get status', this._status)
  298. return this._status
  299. }
  300. get statusText() {
  301. log.verbose('get statusText', this._statusText)
  302. return this._statusText
  303. }
  304. get response() {
  305. log.verbose('get response', this._response)
  306. return this._response
  307. }
  308. get responseText() {
  309. log.verbose('get responseText', this._responseText)
  310. return this._responseText
  311. }
  312. get responseURL() {
  313. log.verbose('get responseURL', this._responseURL)
  314. return this._responseURL
  315. }
  316. get responseHeaders() {
  317. log.verbose('get responseHeaders', this._responseHeaders)
  318. return this._responseHeaders
  319. }
  320. set timeout(val) {
  321. this._timeout = val*1000
  322. log.verbose('set timeout', this._timeout)
  323. }
  324. get timeout() {
  325. log.verbose('get timeout', this._timeout)
  326. return this._timeout
  327. }
  328. set responseType(val) {
  329. log.verbose('set response type', this._responseType)
  330. this._responseType = val
  331. }
  332. get responseType() {
  333. log.verbose('get response type', this._responseType)
  334. return this._responseType
  335. }
  336. }