index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. `use strict`
  2. const http = require('http');
  3. const https = require('https');
  4. const url = require('url');
  5. function getProtocol(path) {
  6. return url.parse(path).protocol === "http:" ? http : https;
  7. }
  8. /**
  9. * Send a get request
  10. * @param path is the url endpoint
  11. * @param headers of the request
  12. * @param callback contains (error, body, status, headers)
  13. */
  14. function get(path, headers, callback) {
  15. request(path, "GET", null, headers, callback);
  16. }
  17. /**
  18. * Send a post request
  19. * @param path is the url endpoint
  20. * @param headers of the request
  21. * @param callback contains (error, body, status, headers)
  22. * @param data a JSON Object or a string
  23. */
  24. function post(path, data, headers, callback) {
  25. request(path, "POST", data, headers, callback);
  26. }
  27. /**
  28. * Send a custom request
  29. * @param path is the url endpoint
  30. * @param headers of the request
  31. * @param callback contains (error, statusCode, data)
  32. * @param data a JSON Object or a string
  33. * @param method is the protocol used like POST GET DELETE PUT etc...
  34. */
  35. function request(path, method, data, headers = '', callback) {
  36. if (typeof data === 'function') {
  37. callback = data;
  38. data = '';
  39. } else if (typeof headers === 'function') {
  40. callback = headers;
  41. headers = {};
  42. }
  43. const postData = typeof data === "object" ? JSON.stringify(data) : data;
  44. const parsedUrl = url.parse(path);
  45. const options = {
  46. hostname: parsedUrl.hostname,
  47. port: parsedUrl.port,
  48. path: parsedUrl.pathname + (!!parsedUrl.search ? parsedUrl.search : ''),
  49. method: method,
  50. headers: headers
  51. };
  52. const req = getProtocol(path).request(options, function (response) {
  53. handleResponse(response, callback);
  54. });
  55. req.on('error', function (error) {
  56. callback(error);
  57. console.error(error);
  58. });
  59. // Write data to request body
  60. if (method !== "GET")
  61. req.write(postData);
  62. req.end();
  63. }
  64. function handleResponse(response, callback) {
  65. let body = '';
  66. const status = response.statusCode;
  67. const hasError = status >= 300;
  68. response.setEncoding('utf8');
  69. response.on('data', function (data) {
  70. body += data;
  71. });
  72. response.on('end', function () {
  73. callback(hasError ? body : null, hasError ? null : body, response.statusCode, response.headers);
  74. });
  75. }
  76. module.exports = {
  77. get,
  78. request,
  79. post
  80. };