PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/react/node_modules/fbjs/node_modules/isomorphic-fetch/node_modules/node-fetch/index.js

https://gitlab.com/aelharrak/react
JavaScript | 222 lines | 54 code | 17 blank | 151 comment | 13 complexity | 17f2e8717410a35c69ce62b3fe254d02 MD5 | raw file
  1. /**
  2. * index.js
  3. *
  4. * a request API compatible with window.fetch
  5. */
  6. var parse_url = require('url').parse;
  7. var resolve_url = require('url').resolve;
  8. var http = require('http');
  9. var https = require('https');
  10. var zlib = require('zlib');
  11. var stream = require('stream');
  12. var Body = require('./lib/body');
  13. var Response = require('./lib/response');
  14. var Headers = require('./lib/headers');
  15. var Request = require('./lib/request');
  16. var FetchError = require('./lib/fetch-error');
  17. // commonjs
  18. module.exports = Fetch;
  19. // es6 default export compatibility
  20. module.exports.default = module.exports;
  21. /**
  22. * Fetch class
  23. *
  24. * @param Mixed url Absolute url or Request instance
  25. * @param Object opts Fetch options
  26. * @return Promise
  27. */
  28. function Fetch(url, opts) {
  29. // allow call as function
  30. if (!(this instanceof Fetch))
  31. return new Fetch(url, opts);
  32. // allow custom promise
  33. if (!Fetch.Promise) {
  34. throw new Error('native promise missing, set Fetch.Promise to your favorite alternative');
  35. }
  36. Body.Promise = Fetch.Promise;
  37. var self = this;
  38. // wrap http.request into fetch
  39. return new Fetch.Promise(function(resolve, reject) {
  40. // build request object
  41. var options;
  42. try {
  43. options = new Request(url, opts);
  44. } catch (err) {
  45. reject(err);
  46. return;
  47. }
  48. var send;
  49. if (options.protocol === 'https:') {
  50. send = https.request;
  51. } else {
  52. send = http.request;
  53. }
  54. // normalize headers
  55. var headers = new Headers(options.headers);
  56. if (options.compress) {
  57. headers.set('accept-encoding', 'gzip,deflate');
  58. }
  59. if (!headers.has('user-agent')) {
  60. headers.set('user-agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
  61. }
  62. if (!headers.has('connection') && !options.agent) {
  63. headers.set('connection', 'close');
  64. }
  65. if (!headers.has('accept')) {
  66. headers.set('accept', '*/*');
  67. }
  68. // detect form data input from form-data module, this hack avoid the need to pass multipart header manually
  69. if (!headers.has('content-type') && options.body && typeof options.body.getBoundary === 'function') {
  70. headers.set('content-type', 'multipart/form-data; boundary=' + options.body.getBoundary());
  71. }
  72. // bring node-fetch closer to browser behavior by setting content-length automatically for POST, PUT, PATCH requests when body is empty or string
  73. if (!headers.has('content-length') && options.method.substr(0, 1).toUpperCase() === 'P') {
  74. if (typeof options.body === 'string') {
  75. headers.set('content-length', Buffer.byteLength(options.body));
  76. // detect form data input from form-data module, this hack avoid the need to add content-length header manually
  77. } else if (options.body && typeof options.body.getLengthSync === 'function') {
  78. headers.set('content-length', options.body.getLengthSync().toString());
  79. // this is only necessary for older nodejs releases (before iojs merge)
  80. } else if (options.body === undefined || options.body === null) {
  81. headers.set('content-length', '0');
  82. }
  83. }
  84. options.headers = headers.raw();
  85. // http.request only support string as host header, this hack make custom host header possible
  86. if (options.headers.host) {
  87. options.headers.host = options.headers.host[0];
  88. }
  89. // send request
  90. var req = send(options);
  91. var reqTimeout;
  92. if (options.timeout) {
  93. req.once('socket', function(socket) {
  94. reqTimeout = setTimeout(function() {
  95. req.abort();
  96. reject(new FetchError('network timeout at: ' + options.url, 'request-timeout'));
  97. }, options.timeout);
  98. });
  99. }
  100. req.on('error', function(err) {
  101. clearTimeout(reqTimeout);
  102. reject(new FetchError('request to ' + options.url + ' failed, reason: ' + err.message, 'system', err));
  103. });
  104. req.on('response', function(res) {
  105. clearTimeout(reqTimeout);
  106. // handle redirect
  107. if (self.isRedirect(res.statusCode) && options.redirect !== 'manual') {
  108. if (options.redirect === 'error') {
  109. reject(new FetchError('redirect mode is set to error: ' + options.url, 'no-redirect'));
  110. return;
  111. }
  112. if (options.counter >= options.follow) {
  113. reject(new FetchError('maximum redirect reached at: ' + options.url, 'max-redirect'));
  114. return;
  115. }
  116. if (!res.headers.location) {
  117. reject(new FetchError('redirect location header missing at: ' + options.url, 'invalid-redirect'));
  118. return;
  119. }
  120. // per fetch spec, for POST request with 301/302 response, or any request with 303 response, use GET when following redirect
  121. if (res.statusCode === 303
  122. || ((res.statusCode === 301 || res.statusCode === 302) && options.method === 'POST'))
  123. {
  124. options.method = 'GET';
  125. delete options.body;
  126. delete options.headers['content-length'];
  127. }
  128. options.counter++;
  129. resolve(Fetch(resolve_url(options.url, res.headers.location), options));
  130. return;
  131. }
  132. // handle compression
  133. var body = res.pipe(new stream.PassThrough());
  134. var headers = new Headers(res.headers);
  135. if (options.compress && headers.has('content-encoding')) {
  136. var name = headers.get('content-encoding');
  137. if (name == 'gzip' || name == 'x-gzip') {
  138. body = body.pipe(zlib.createGunzip());
  139. } else if (name == 'deflate' || name == 'x-deflate') {
  140. body = body.pipe(zlib.createInflate());
  141. }
  142. }
  143. // normalize location header for manual redirect mode
  144. if (options.redirect === 'manual' && headers.has('location')) {
  145. headers.set('location', resolve_url(options.url, headers.get('location')));
  146. }
  147. // response object
  148. var output = new Response(body, {
  149. url: options.url
  150. , status: res.statusCode
  151. , statusText: res.statusMessage
  152. , headers: headers
  153. , size: options.size
  154. , timeout: options.timeout
  155. });
  156. resolve(output);
  157. });
  158. // accept string or readable stream as body
  159. if (typeof options.body === 'string') {
  160. req.write(options.body);
  161. req.end();
  162. } else if (typeof options.body === 'object' && options.body.pipe) {
  163. options.body.pipe(req);
  164. } else {
  165. req.end();
  166. }
  167. });
  168. };
  169. /**
  170. * Redirect code matching
  171. *
  172. * @param Number code Status code
  173. * @return Boolean
  174. */
  175. Fetch.prototype.isRedirect = function(code) {
  176. return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
  177. }
  178. // expose Promise
  179. Fetch.Promise = global.Promise;
  180. Fetch.Response = Response;
  181. Fetch.Headers = Headers;
  182. Fetch.Request = Request;