Request.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. const url = require('url');
  2. const http = require('http');
  3. const https = require('https');
  4. const jsonToURL = require('../commons/jsonToParameter');
  5. function getProtocol(path) {
  6. return url.parse(path).protocol === "http:" ? http : https;
  7. }
  8. const Request = function() {
  9. let _options = {};
  10. let _requestOptions = {
  11. followRedirect: true,
  12. maxRedirect: 3,
  13. trustRedirect: true
  14. };
  15. let _parsedUrl;
  16. let _originalPath; //String
  17. let _postData; //String
  18. let _callback = ()=>{};
  19. this._handleResponse = function(response, callback) {
  20. let body = '';
  21. const status = response.statusCode;
  22. const hasError = status >= 300;
  23. response.setEncoding('utf8');
  24. response.on('data', function(data) {
  25. body += data;
  26. });
  27. response.on('end', () => {
  28. //used to manage 3xx calls
  29. if (status >= 300 && status < 400 && !!response.headers && !!response.headers.location) {
  30. if (!_requestOptions.followRedirect) {
  31. callback(JSON.stringify({code: 0, message: "ForwardRedirect is disabled"}),null, response.statusCode, response.headers)
  32. return;
  33. }
  34. if (!!_requestOptions.currentRedirect) {
  35. if (_requestOptions.currentRedirect == _requestOptions.maxRedirect) {
  36. callback(JSON.stringify({code: 1, message: "Max redirects exceeded"}),null, response.statusCode, response.headers)
  37. return;
  38. }
  39. _requestOptions.currentRedirect +=1
  40. } else {
  41. _requestOptions.currentRedirect = 1;
  42. }
  43. if (!_requestOptions.trustRedirect) {
  44. _options.headers = {};
  45. }
  46. this._parsePath(response.headers.location);
  47. this.sendRequest();
  48. return;
  49. }
  50. callback(hasError ? body : null, hasError ? null : body, response.statusCode, response.headers);
  51. });
  52. }
  53. this.setCookies = function(body) {
  54. if (!body) {
  55. return;
  56. }
  57. if (typeof body == "object") {
  58. body = jsonToURL(body);
  59. }
  60. if (!_options.headers) {
  61. _options.headers = {};
  62. }
  63. _options.headers.Cookie = body;
  64. }
  65. this._parsePath = function(path) {
  66. if (!!_parsedUrl && !!path && path.indexOf('http') == -1) {
  67. path = _parsedUrl.protocol + "//" + _parsedUrl.host + path;
  68. }
  69. _originalPath = path;
  70. _parsedUrl = url.parse(path);
  71. _options.hostname = _parsedUrl.hostname;
  72. _options.port = _parsedUrl.port;
  73. _options.path = _parsedUrl.pathname + (!!_parsedUrl.search ? _parsedUrl.search : '');
  74. }
  75. this.sendRequest = function() {
  76. if (!!_options.headers && (!_options.headers['content-type'] && !_options.headers['Content-Type'])) {
  77. _options.headers['content-type'] = 'application/json';
  78. }
  79. const req = getProtocol(_originalPath).request(_options, (response) => {
  80. this._handleResponse(response, _callback);
  81. });
  82. req.on('error', function(error) {
  83. _callback(error);
  84. });
  85. // Write data to request body
  86. if (_options.method !== "GET")
  87. req.write(_postData);
  88. req.end();
  89. }
  90. /**
  91. * Send a custom request
  92. * @param path is the url endpoint
  93. * @param headers of the request
  94. * @param callback contains (error, statusCode, data)
  95. * @param data a JSON Object or a string
  96. * @param method is the protocol used like POST GET DELETE PUT etc...
  97. */
  98. this.createRequest = function(path, method, data, headers = {}, requestOptions = {}, callback) {
  99. if (typeof data === 'function') {
  100. callback = data;
  101. data = '';
  102. } else if (typeof headers === 'function') {
  103. callback = headers;
  104. headers = {};
  105. } else if (typeof requestOptions === 'function') {
  106. callback = requestOptions;
  107. }
  108. const postData = typeof data === "object" ? JSON.stringify(data) : data;
  109. _options = {
  110. method: method,
  111. headers: headers
  112. };
  113. this._parsePath(path);
  114. _postData = postData;
  115. for (const key of Object.keys(_requestOptions)) {
  116. if (key in requestOptions) {
  117. _requestOptions[key] = requestOptions[key];
  118. }
  119. }
  120. _callback = callback;
  121. }
  122. }
  123. module.exports = Request;