i18nextXHRBackend.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.i18nextXHRBackend = factory());
  5. }(this, (function () { 'use strict';
  6. var arr = [];
  7. var each = arr.forEach;
  8. var slice = arr.slice;
  9. function defaults(obj) {
  10. each.call(slice.call(arguments, 1), function (source) {
  11. if (source) {
  12. for (var prop in source) {
  13. if (obj[prop] === undefined) obj[prop] = source[prop];
  14. }
  15. }
  16. });
  17. return obj;
  18. }
  19. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  20. function addQueryString(url, params) {
  21. if (params && (typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
  22. var queryString = '',
  23. e = encodeURIComponent;
  24. // Must encode data
  25. for (var paramName in params) {
  26. queryString += '&' + e(paramName) + '=' + e(params[paramName]);
  27. }
  28. if (!queryString) {
  29. return url;
  30. }
  31. url = url + (url.indexOf('?') !== -1 ? '&' : '?') + queryString.slice(1);
  32. }
  33. return url;
  34. }
  35. // https://gist.github.com/Xeoncross/7663273
  36. function ajax(url, options, callback, data, cache) {
  37. if (data && (typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') {
  38. if (!cache) {
  39. data['_t'] = new Date();
  40. }
  41. // URL encoded form data must be in querystring format
  42. data = addQueryString('', data).slice(1);
  43. }
  44. if (options.queryStringParams) {
  45. url = addQueryString(url, options.queryStringParams);
  46. }
  47. try {
  48. var x;
  49. if (XMLHttpRequest) {
  50. x = new XMLHttpRequest();
  51. } else {
  52. x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
  53. }
  54. x.open(data ? 'POST' : 'GET', url, 1);
  55. if (!options.crossDomain) {
  56. x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  57. }
  58. x.withCredentials = !!options.withCredentials;
  59. if (data) {
  60. x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  61. }
  62. if (x.overrideMimeType) {
  63. x.overrideMimeType("application/json");
  64. }
  65. var h = options.customHeaders;
  66. if (h) {
  67. for (var i in h) {
  68. x.setRequestHeader(i, h[i]);
  69. }
  70. }
  71. x.onreadystatechange = function () {
  72. x.readyState > 3 && callback && callback(x.responseText, x);
  73. };
  74. x.send(data);
  75. } catch (e) {
  76. console && console.log(e);
  77. }
  78. }
  79. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  80. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  81. function getDefaults() {
  82. return {
  83. loadPath: '/locales/{{lng}}/{{ns}}.json',
  84. addPath: '/locales/add/{{lng}}/{{ns}}',
  85. allowMultiLoading: false,
  86. parse: JSON.parse,
  87. crossDomain: false,
  88. ajax: ajax
  89. };
  90. }
  91. var Backend = function () {
  92. function Backend(services) {
  93. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  94. _classCallCheck(this, Backend);
  95. this.init(services, options);
  96. this.type = 'backend';
  97. }
  98. _createClass(Backend, [{
  99. key: 'init',
  100. value: function init(services) {
  101. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  102. this.services = services;
  103. this.options = defaults(options, this.options || {}, getDefaults());
  104. }
  105. }, {
  106. key: 'readMulti',
  107. value: function readMulti(languages, namespaces, callback) {
  108. var loadPath = this.options.loadPath;
  109. if (typeof this.options.loadPath === 'function') {
  110. loadPath = this.options.loadPath(languages, namespaces);
  111. }
  112. var url = this.services.interpolator.interpolate(loadPath, { lng: languages.join('+'), ns: namespaces.join('+') });
  113. this.loadUrl(url, callback);
  114. }
  115. }, {
  116. key: 'read',
  117. value: function read(language, namespace, callback) {
  118. var loadPath = this.options.loadPath;
  119. if (typeof this.options.loadPath === 'function') {
  120. loadPath = this.options.loadPath([language], [namespace]);
  121. }
  122. var url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace });
  123. this.loadUrl(url, callback);
  124. }
  125. }, {
  126. key: 'loadUrl',
  127. value: function loadUrl(url, callback) {
  128. var _this = this;
  129. this.options.ajax(url, this.options, function (data, xhr) {
  130. if (xhr.status >= 500 && xhr.status < 600) return callback('failed loading ' + url, true /* retry */);
  131. if (xhr.status >= 400 && xhr.status < 500) return callback('failed loading ' + url, false /* no retry */);
  132. var ret = void 0,
  133. err = void 0;
  134. try {
  135. ret = _this.options.parse(data, url);
  136. } catch (e) {
  137. err = 'failed parsing ' + url + ' to json';
  138. }
  139. if (err) return callback(err, false);
  140. callback(null, ret);
  141. });
  142. }
  143. }, {
  144. key: 'create',
  145. value: function create(languages, namespace, key, fallbackValue) {
  146. var _this2 = this;
  147. if (typeof languages === 'string') languages = [languages];
  148. var payload = {};
  149. payload[key] = fallbackValue || '';
  150. languages.forEach(function (lng) {
  151. var url = _this2.services.interpolator.interpolate(_this2.options.addPath, { lng: lng, ns: namespace });
  152. _this2.options.ajax(url, _this2.options, function (data, xhr) {
  153. //const statusCode = xhr.status.toString();
  154. // TODO: if statusCode === 4xx do log
  155. }, payload);
  156. });
  157. }
  158. }]);
  159. return Backend;
  160. }();
  161. Backend.type = 'backend';
  162. return Backend;
  163. })));