UNPKG

7.25 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global = global || self, global.i18nextXHRBackend = factory());
5}(this, function () { 'use strict';
6
7 function _classCallCheck(instance, Constructor) {
8 if (!(instance instanceof Constructor)) {
9 throw new TypeError("Cannot call a class as a function");
10 }
11 }
12
13 function _defineProperties(target, props) {
14 for (var i = 0; i < props.length; i++) {
15 var descriptor = props[i];
16 descriptor.enumerable = descriptor.enumerable || false;
17 descriptor.configurable = true;
18 if ("value" in descriptor) descriptor.writable = true;
19 Object.defineProperty(target, descriptor.key, descriptor);
20 }
21 }
22
23 function _createClass(Constructor, protoProps, staticProps) {
24 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
25 if (staticProps) _defineProperties(Constructor, staticProps);
26 return Constructor;
27 }
28
29 var arr = [];
30 var each = arr.forEach;
31 var slice = arr.slice;
32 function defaults(obj) {
33 each.call(slice.call(arguments, 1), function (source) {
34 if (source) {
35 for (var prop in source) {
36 if (obj[prop] === undefined) obj[prop] = source[prop];
37 }
38 }
39 });
40 return obj;
41 }
42
43 function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
44
45 function _typeof(obj) {
46 if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
47 _typeof = function _typeof(obj) {
48 return _typeof2(obj);
49 };
50 } else {
51 _typeof = function _typeof(obj) {
52 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
53 };
54 }
55
56 return _typeof(obj);
57 }
58
59 function addQueryString(url, params) {
60 if (params && _typeof(params) === 'object') {
61 var queryString = '',
62 e = encodeURIComponent; // Must encode data
63
64 for (var paramName in params) {
65 queryString += '&' + e(paramName) + '=' + e(params[paramName]);
66 }
67
68 if (!queryString) {
69 return url;
70 }
71
72 url = url + (url.indexOf('?') !== -1 ? '&' : '?') + queryString.slice(1);
73 }
74
75 return url;
76 } // https://gist.github.com/Xeoncross/7663273
77
78
79 function ajax(url, options, callback, data, cache) {
80 if (data && _typeof(data) === 'object') {
81 if (!cache) {
82 data['_t'] = new Date();
83 } // URL encoded form data must be in querystring format
84
85
86 data = addQueryString('', data).slice(1);
87 }
88
89 if (options.queryStringParams) {
90 url = addQueryString(url, options.queryStringParams);
91 }
92
93 try {
94 var x;
95
96 if (XMLHttpRequest) {
97 x = new XMLHttpRequest();
98 } else {
99 x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
100 }
101
102 x.open(data ? 'POST' : 'GET', url, 1);
103
104 if (!options.crossDomain) {
105 x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
106 }
107
108 x.withCredentials = !!options.withCredentials;
109
110 if (data) {
111 x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
112 }
113
114 if (x.overrideMimeType) {
115 x.overrideMimeType("application/json");
116 }
117
118 var h = options.customHeaders;
119 h = typeof h === 'function' ? h() : h;
120
121 if (h) {
122 for (var i in h) {
123 x.setRequestHeader(i, h[i]);
124 }
125 }
126
127 x.onreadystatechange = function () {
128 x.readyState > 3 && callback && callback(x.responseText, x);
129 };
130
131 x.send(data);
132 } catch (e) {
133 console && console.log(e);
134 }
135 }
136
137 function getDefaults() {
138 return {
139 loadPath: '/locales/{{lng}}/{{ns}}.json',
140 addPath: '/locales/add/{{lng}}/{{ns}}',
141 allowMultiLoading: false,
142 parse: JSON.parse,
143 crossDomain: false,
144 ajax: ajax
145 };
146 }
147
148 var Backend =
149 /*#__PURE__*/
150 function () {
151 function Backend(services) {
152 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
153
154 _classCallCheck(this, Backend);
155
156 this.init(services, options);
157 this.type = 'backend';
158 }
159
160 _createClass(Backend, [{
161 key: "init",
162 value: function init(services) {
163 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
164 this.services = services;
165 this.options = defaults(options, this.options || {}, getDefaults());
166 }
167 }, {
168 key: "readMulti",
169 value: function readMulti(languages, namespaces, callback) {
170 var loadPath = this.options.loadPath;
171
172 if (typeof this.options.loadPath === 'function') {
173 loadPath = this.options.loadPath(languages, namespaces);
174 }
175
176 var url = this.services.interpolator.interpolate(loadPath, {
177 lng: languages.join('+'),
178 ns: namespaces.join('+')
179 });
180 this.loadUrl(url, callback);
181 }
182 }, {
183 key: "read",
184 value: function read(language, namespace, callback) {
185 var loadPath = this.options.loadPath;
186
187 if (typeof this.options.loadPath === 'function') {
188 loadPath = this.options.loadPath([language], [namespace]);
189 }
190
191 var url = this.services.interpolator.interpolate(loadPath, {
192 lng: language,
193 ns: namespace
194 });
195 this.loadUrl(url, callback);
196 }
197 }, {
198 key: "loadUrl",
199 value: function loadUrl(url, callback) {
200 var _this = this;
201
202 this.options.ajax(url, this.options, function (data, xhr) {
203 if (xhr.status >= 500 && xhr.status < 600) return callback('failed loading ' + url, true
204 /* retry */
205 );
206 if (xhr.status >= 400 && xhr.status < 500) return callback('failed loading ' + url, false
207 /* no retry */
208 );
209 var ret, err;
210
211 try {
212 ret = _this.options.parse(data, url);
213 } catch (e) {
214 err = 'failed parsing ' + url + ' to json';
215 }
216
217 if (err) return callback(err, false);
218 callback(null, ret);
219 });
220 }
221 }, {
222 key: "create",
223 value: function create(languages, namespace, key, fallbackValue) {
224 var _this2 = this;
225
226 if (typeof languages === 'string') languages = [languages];
227 var payload = {};
228 payload[key] = fallbackValue || '';
229 languages.forEach(function (lng) {
230 var url = _this2.services.interpolator.interpolate(_this2.options.addPath, {
231 lng: lng,
232 ns: namespace
233 });
234
235 _this2.options.ajax(url, _this2.options, function (data, xhr) {//const statusCode = xhr.status.toString();
236 // TODO: if statusCode === 4xx do log
237 }, payload);
238 });
239 }
240 }]);
241
242 return Backend;
243 }();
244
245 Backend.type = 'backend';
246
247 return Backend;
248
249}));