base.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ApiRequest = void 0;
  4. const got = require("got");
  5. const pkg = require("../../package.json");
  6. class ApiRequest {
  7. urlRoot = "https://api.lokalise.com/api2/";
  8. promise;
  9. params = {};
  10. constructor(uri, method, body, params, clientData) {
  11. this.params = params;
  12. this.promise = this.createPromise(uri, method, body, clientData);
  13. return this;
  14. }
  15. async createPromise(uri, method, body, clientData) {
  16. const options = {
  17. method: method,
  18. prefixUrl: clientData.host ?? this.urlRoot,
  19. headers: {
  20. "User-Agent": `node-lokalise-api/${pkg.version}`,
  21. },
  22. agent: false,
  23. throwHttpErrors: false,
  24. decompress: false,
  25. };
  26. /* istanbul ignore next */
  27. if (!options["headers"]) {
  28. /* istanbul ignore next */
  29. options["headers"] = {};
  30. }
  31. options["headers"][clientData.authHeader] = `${clientData.tokenType} ${clientData.token}`;
  32. if (clientData.enableCompression) {
  33. options["headers"]["Accept-Encoding"] = "gzip,deflate";
  34. options["decompress"] = true;
  35. }
  36. const url = this.composeURI(uri);
  37. if (Object.keys(this.params).length > 0) {
  38. const formattedParams = new URLSearchParams(this.params);
  39. options["searchParams"] = formattedParams.toString();
  40. }
  41. if (method !== "GET" && body) {
  42. options["body"] = JSON.stringify(body);
  43. }
  44. try {
  45. const response = await got(url, options);
  46. const responseJSON = JSON.parse(response.body);
  47. if (response.statusCode > 399) {
  48. return Promise.reject(responseJSON["error"] || responseJSON);
  49. }
  50. return Promise.resolve({ json: responseJSON, headers: response.headers });
  51. }
  52. catch (err) {
  53. /* istanbul ignore next */
  54. return Promise.reject(err);
  55. }
  56. }
  57. composeURI(rawUri) {
  58. const regexp = /{(!{0,1}):(\w*)}/g;
  59. const uri = rawUri.replace(regexp, this.mapUriParams(this.params));
  60. return uri.endsWith("/") ? uri.slice(0, -1) : uri;
  61. }
  62. mapUriParams(params) {
  63. return (_entity, isMandaratory, paramName) => {
  64. if (params[paramName] != null) {
  65. const t_param = params[paramName];
  66. delete this.params[paramName];
  67. return t_param;
  68. }
  69. else {
  70. if (isMandaratory === "!") {
  71. throw new Error("Required param " + paramName);
  72. }
  73. else {
  74. return "";
  75. }
  76. }
  77. };
  78. }
  79. }
  80. exports.ApiRequest = ApiRequest;
  81. //# sourceMappingURL=base.js.map