You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.6 KiB

  1. package utils;
  2. import haxe.Json;
  3. import js.Promise;
  4. import js.html.XMLHttpRequest;
  5. @:enum abstract HttpMethod(String) to String {
  6. var POST = 'POST';
  7. var GET = 'GET';
  8. var HEAD = 'HEAD';
  9. var PUT = 'PUT';
  10. var DELETE = 'DELETE';
  11. var TRACE = 'TRACE';
  12. var OPTIONS = 'OPTIONS';
  13. var CONNECT = 'CONNECT';
  14. var PATCH = 'GET';
  15. }
  16. @:enum abstract FetchFormat(String) from String to String {
  17. var PLAIN_TEXT = "text/plain";
  18. var JSON = "application/json";
  19. }
  20. //json version of a tink.core.Error
  21. typedef ErrorInfos = {error:{code:Int,message:String,stack:String}}
  22. /**
  23. * Manage HTTP request to a REST API.
  24. *
  25. * POST requests can only have a single JSON object (payload)
  26. */
  27. class HttpUtil
  28. {
  29. static public function fetch(
  30. url: String,
  31. ?method: HttpMethod = GET,
  32. ?params: Dynamic = null,
  33. ?accept: FetchFormat = PLAIN_TEXT,
  34. ?contentType: String = JSON
  35. ): Promise<Dynamic> {
  36. return new Promise(function(resolve: Dynamic->Void, reject) {
  37. var data: String = null;
  38. if (params != null)
  39. {
  40. if (params.body != null){
  41. data = Json.stringify(params.body);
  42. } else if(method==POST) {
  43. data = Json.stringify(params);
  44. } else {
  45. url += (url.indexOf('?') > -1) ? '&' : '?';
  46. url += objToString(params);
  47. }
  48. }
  49. var http = new XMLHttpRequest();
  50. http.open(method, url, true);
  51. if (contentType != null && contentType.length > 0)
  52. http.setRequestHeader("Content-type", contentType);
  53. if (accept != null)
  54. http.setRequestHeader("Accept", accept);
  55. http.onreadystatechange = function() {
  56. //trace("readystate",http.readyState, http.status);
  57. if (http.readyState == 4){
  58. switch (http.status){
  59. case 200:
  60. switch (accept){
  61. case JSON:
  62. try {
  63. var json = Json.parse(http.responseText);
  64. resolve(json);
  65. } catch (err: Dynamic){
  66. reject(err);
  67. }
  68. default:
  69. resolve(http.responseText);
  70. }
  71. case 204:
  72. resolve(true);
  73. default:
  74. reject(http.responseText);
  75. }
  76. }
  77. };
  78. http.send(data);
  79. });
  80. }
  81. static public function objToString(obj: Dynamic): String
  82. {
  83. var str = "";
  84. var cpt = 0;
  85. for (key in Reflect.fields(obj))
  86. {
  87. var value: Dynamic = Reflect.field(obj, key);
  88. if (value == null) continue;
  89. if (cpt++ > 0)
  90. str += "&";
  91. if (Std.is(value, Array) && value.length > 0)
  92. str += '$key=${value.join(";")}';
  93. else if (Std.string(value) != "") // String / Int / Float
  94. str += '$key=${StringTools.trim(Std.string(value))}';
  95. }
  96. return str;
  97. }
  98. }