@nextgis/ngw-connector 1.16.8 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1136 +1,998 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 1.16.8; author: NextGIS */
1
+ /** Bundle of @nextgis/ngw-connector; version: 1.17.0; author: NextGIS */
2
2
  import { EventEmitter } from 'events';
3
3
  import CancelablePromise from '@nextgis/cancelable-promise';
4
4
  import { objectDeepEqual, defined, objectRemoveEmpty, fixUrlStr } from '@nextgis/utils';
5
5
  import Cache from '@nextgis/cache';
6
6
 
7
- /******************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
- /* global Reflect, Promise */
22
-
23
- var extendStatics = function(d, b) {
24
- extendStatics = Object.setPrototypeOf ||
25
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
27
- return extendStatics(d, b);
28
- };
29
-
30
- function __extends(d, b) {
31
- if (typeof b !== "function" && b !== null)
32
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
33
- extendStatics(d, b);
34
- function __() { this.constructor = d; }
35
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36
- }
37
-
38
- var __assign = function() {
39
- __assign = Object.assign || function __assign(t) {
40
- for (var s, i = 1, n = arguments.length; i < n; i++) {
41
- s = arguments[i];
42
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
43
- }
44
- return t;
45
- };
46
- return __assign.apply(this, arguments);
47
- };
48
-
49
- function __awaiter(thisArg, _arguments, P, generator) {
50
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
51
- return new (P || (P = Promise))(function (resolve, reject) {
52
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
53
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
54
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
55
- step((generator = generator.apply(thisArg, _arguments || [])).next());
56
- });
57
- }
58
-
59
- function __generator(thisArg, body) {
60
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
61
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
62
- function verb(n) { return function (v) { return step([n, v]); }; }
63
- function step(op) {
64
- if (f) throw new TypeError("Generator is already executing.");
65
- while (_) try {
66
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
67
- if (y = 0, t) op = [op[0] & 2, t.value];
68
- switch (op[0]) {
69
- case 0: case 1: t = op; break;
70
- case 4: _.label++; return { value: op[1], done: false };
71
- case 5: _.label++; y = op[1]; op = [0]; continue;
72
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
73
- default:
74
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
75
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
76
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
77
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
78
- if (t[2]) _.ops.pop();
79
- _.trys.pop(); continue;
80
- }
81
- op = body.call(thisArg, _);
82
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
83
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
84
- }
85
- }
86
-
87
- function __spreadArray(to, from, pack) {
88
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
89
- if (ar || !(i in from)) {
90
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
91
- ar[i] = from[i];
92
- }
93
- }
94
- return to.concat(ar || Array.prototype.slice.call(from));
7
+ /**
8
+ * Thrown when...
9
+ */
10
+ class NetworkError extends Error {
11
+ constructor(url) {
12
+ super();
13
+ this.name = 'NetworkError';
14
+ Object.setPrototypeOf(this, NetworkError.prototype);
15
+ this.message = `Unable to request ${url}.
16
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors
17
+ }
95
18
  }
96
19
 
97
- /**
98
- * Thrown when...
99
- */
100
- var NetworkError = /** @class */ (function (_super) {
101
- __extends(NetworkError, _super);
102
- function NetworkError(url) {
103
- var _this = _super.call(this) || this;
104
- _this.name = 'NetworkError';
105
- Object.setPrototypeOf(_this, NetworkError.prototype);
106
- _this.message = "Unable to request ".concat(url, ".\n Possibly invalid NGW URL entered or CORS not configured to get request from ").concat(location.origin); // /control-panel/cors
107
- return _this;
108
- }
109
- return NetworkError;
110
- }(Error));
111
-
112
- /**
113
- * Thrown when...
114
- */
115
- var NgwError = /** @class */ (function (_super) {
116
- __extends(NgwError, _super);
117
- function NgwError(er) {
118
- var _this = _super.call(this) || this;
119
- _this.name = 'NgwError';
120
- Object.assign(_this, er);
121
- Object.setPrototypeOf(_this, NgwError.prototype);
122
- return _this;
123
- }
124
- return NgwError;
125
- }(Error));
20
+ /**
21
+ * Thrown when...
22
+ */
23
+ class NgwError extends Error {
24
+ constructor(er) {
25
+ super();
26
+ this.name = 'NgwError';
27
+ Object.assign(this, er);
28
+ Object.setPrototypeOf(this, NgwError.prototype);
29
+ }
30
+ }
126
31
 
127
- function isObject(val) {
128
- return Object.prototype.toString.call(val) === '[object Object]';
32
+ function isObject(val) {
33
+ return Object.prototype.toString.call(val) === '[object Object]';
129
34
  }
130
35
 
131
- var loadData;
132
- // @ts-ignore
133
- {
134
- loadData = function (url, callback, options, error, onCancel) {
135
- if (options === void 0) { options = {}; }
136
- options.method = options.method || 'GET';
137
- var xhr = new XMLHttpRequest();
138
- xhr.open(options.method || 'GET', url, true); // true for asynchronous
139
- if (options.responseType === 'blob') {
140
- xhr.responseType = options.responseType;
141
- }
142
- var getResponseText = function () {
143
- try {
144
- return JSON.parse(xhr.responseText);
145
- }
146
- catch (er) {
147
- return xhr.responseText;
148
- }
149
- };
150
- var processingResponse = function (forError) {
151
- if (forError === void 0) { forError = false; }
152
- var cb = forError ? error : callback;
153
- if (options.responseType === 'blob') {
154
- cb(xhr.response);
155
- }
156
- else {
157
- if (xhr.responseText) {
158
- cb(getResponseText());
159
- }
160
- else {
161
- error({ message: '' });
162
- }
163
- }
164
- };
165
- xhr.onload = function () {
166
- if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
167
- error(new NgwError(getResponseText()));
168
- }
169
- processingResponse();
170
- };
171
- // xhr.onreadystatechange = () => {
172
- // if (
173
- // (xhr.readyState === 4 && xhr.status === 200) ||
174
- // (xhr.readyState === 3 && xhr.status === 201)
175
- // ) {
176
- // processingResponse();
177
- // } else if (xhr.readyState === 3 && xhr.status === 400) {
178
- // processingResponse();
179
- // } else if (xhr.readyState === 4 && xhr.status === 500) {
180
- // processingResponse();
181
- // } else if (xhr.readyState === 4 && xhr.status === 401) {
182
- // error(xhr.statusText);
183
- // } else if (xhr.readyState === 4) {
184
- // error('request error');
185
- // }
186
- // };
187
- xhr.onerror = function (er) {
188
- if (xhr.status === 0) {
189
- error(new NetworkError(url));
190
- }
191
- else {
192
- error(er);
193
- }
194
- };
195
- xhr.upload.onprogress = function (e) {
196
- if (e.lengthComputable) {
197
- var percentComplete = (e.loaded / e.total) * 100;
198
- if (options.onProgress) {
199
- options.onProgress(percentComplete, e);
200
- }
201
- // console.log(percentComplete + '% uploaded');
202
- }
203
- };
204
- var headers = options.headers;
205
- if (headers) {
206
- for (var h in headers) {
207
- var header = headers[h];
208
- if (typeof header === 'string') {
209
- xhr.setRequestHeader(h, header);
210
- }
211
- }
212
- }
213
- if (options.withCredentials !== undefined) {
214
- xhr.withCredentials = options.withCredentials;
215
- }
216
- var data;
217
- if (options.file) {
218
- data = new FormData();
219
- data.append('file', options.file);
220
- if (options.data) {
221
- for (var d in options.data) {
222
- data.append(d, data[d]);
223
- }
224
- }
225
- }
226
- else {
227
- data = options.data
228
- ? typeof options.data === 'string'
229
- ? options.data
230
- : JSON.stringify(options.data)
231
- : null;
232
- }
233
- if (onCancel) {
234
- onCancel(function () {
235
- xhr.abort();
236
- });
237
- }
238
- xhr.send(data);
239
- };
36
+ let loadData;
37
+ // @ts-ignore
38
+ {
39
+ loadData = (url, callback, options = {}, error, onCancel) => {
40
+ options.method = options.method || 'GET';
41
+ const xhr = new XMLHttpRequest();
42
+ xhr.open(options.method || 'GET', url, true); // true for asynchronous
43
+ if (options.responseType === 'blob') {
44
+ xhr.responseType = options.responseType;
45
+ }
46
+ const getResponseText = () => {
47
+ try {
48
+ return JSON.parse(xhr.responseText);
49
+ }
50
+ catch (er) {
51
+ return xhr.responseText;
52
+ }
53
+ };
54
+ const processingResponse = (forError = false) => {
55
+ const cb = forError ? error : callback;
56
+ if (options.responseType === 'blob') {
57
+ cb(xhr.response);
58
+ }
59
+ else {
60
+ if (xhr.responseText) {
61
+ cb(getResponseText());
62
+ }
63
+ else {
64
+ error({ message: '' });
65
+ }
66
+ }
67
+ };
68
+ xhr.onload = () => {
69
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
70
+ error(new NgwError(getResponseText()));
71
+ }
72
+ processingResponse();
73
+ };
74
+ // xhr.onreadystatechange = () => {
75
+ // if (
76
+ // (xhr.readyState === 4 && xhr.status === 200) ||
77
+ // (xhr.readyState === 3 && xhr.status === 201)
78
+ // ) {
79
+ // processingResponse();
80
+ // } else if (xhr.readyState === 3 && xhr.status === 400) {
81
+ // processingResponse();
82
+ // } else if (xhr.readyState === 4 && xhr.status === 500) {
83
+ // processingResponse();
84
+ // } else if (xhr.readyState === 4 && xhr.status === 401) {
85
+ // error(xhr.statusText);
86
+ // } else if (xhr.readyState === 4) {
87
+ // error('request error');
88
+ // }
89
+ // };
90
+ xhr.onerror = (er) => {
91
+ if (xhr.status === 0) {
92
+ error(new NetworkError(url));
93
+ }
94
+ else {
95
+ error(er);
96
+ }
97
+ };
98
+ xhr.upload.onprogress = function (e) {
99
+ if (e.lengthComputable) {
100
+ const percentComplete = (e.loaded / e.total) * 100;
101
+ if (options.onProgress) {
102
+ options.onProgress(percentComplete, e);
103
+ }
104
+ // console.log(percentComplete + '% uploaded');
105
+ }
106
+ };
107
+ const headers = options.headers;
108
+ if (headers) {
109
+ for (const h in headers) {
110
+ const header = headers[h];
111
+ if (typeof header === 'string') {
112
+ xhr.setRequestHeader(h, header);
113
+ }
114
+ }
115
+ }
116
+ if (options.withCredentials !== undefined) {
117
+ xhr.withCredentials = options.withCredentials;
118
+ }
119
+ let data;
120
+ if (options.file) {
121
+ data = new FormData();
122
+ data.append('file', options.file);
123
+ if (options.data) {
124
+ for (const d in options.data) {
125
+ data.append(d, data[d]);
126
+ }
127
+ }
128
+ }
129
+ else {
130
+ data = options.data
131
+ ? typeof options.data === 'string'
132
+ ? options.data
133
+ : JSON.stringify(options.data)
134
+ : null;
135
+ }
136
+ if (onCancel) {
137
+ onCancel(() => {
138
+ xhr.abort();
139
+ });
140
+ }
141
+ xhr.send(data);
142
+ };
240
143
  }
241
144
 
242
- // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
243
- var templateRe = /\{ *([\w_-]+) *\}/g;
244
- function template(str, data) {
245
- return str.replace(templateRe, function (s, key) {
246
- var value = data[key];
247
- if (value === undefined) {
248
- throw new Error('No value provided for letiable ' + s);
249
- }
250
- else if (typeof value === 'function') {
251
- value = value(data);
252
- }
253
- return value;
254
- });
145
+ // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
146
+ const templateRe = /\{ *([\w_-]+) *\}/g;
147
+ function template(str, data) {
148
+ return str.replace(templateRe, (s, key) => {
149
+ let value = data[key];
150
+ if (value === undefined) {
151
+ throw new Error('No value provided for letiable ' + s);
152
+ }
153
+ else if (typeof value === 'function') {
154
+ value = value(data);
155
+ }
156
+ return value;
157
+ });
255
158
  }
256
159
 
257
- function apiRequest(opt) {
258
- var params = opt.params;
259
- return new CancelablePromise(function (resolve, reject) {
260
- opt.connector
261
- .connect()
262
- .then(function (apiItems) {
263
- var apiItem = apiItems && apiItems[opt.name];
264
- if (apiItem) {
265
- apiItem = __spreadArray([], apiItem, true);
266
- var url = apiItem.shift();
267
- if (apiItem.length) {
268
- var replaceParams = {};
269
- for (var fry = 0; fry < apiItem.length; fry++) {
270
- var arg = apiItem[fry];
271
- replaceParams[fry] = '{' + arg + '}';
272
- if (params[arg] === undefined) {
273
- throw new Error('`' + arg + '`' + ' url api argument is not specified');
274
- }
275
- }
276
- if (url) {
277
- url = template(url, replaceParams);
278
- }
279
- }
280
- // Transfer part of the parameters from `params` to the URL string
281
- if (params) {
282
- var paramArray_1 = [];
283
- var paramList = params.paramList;
284
- if (Array.isArray(paramList)) {
285
- delete params.paramList;
286
- paramList.forEach(function (x) {
287
- paramArray_1.push("".concat(x[0], "=").concat(x[1]));
288
- });
289
- }
290
- for (var p in params) {
291
- if (apiItem.indexOf(p) === -1) {
292
- paramArray_1.push("".concat(p, "=").concat(params[p]));
293
- }
294
- }
295
- if (paramArray_1.length) {
296
- url = url + '?' + paramArray_1.join('&');
297
- }
298
- }
299
- if (url) {
300
- resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
301
- }
302
- else {
303
- reject(new Error('request url is not set'));
304
- }
305
- }
306
- else {
307
- resolve(undefined);
308
- }
309
- })
310
- .catch(function (er) {
311
- reject(er);
312
- });
313
- });
160
+ function apiRequest(opt) {
161
+ const params = opt.params;
162
+ return new CancelablePromise((resolve, reject) => {
163
+ opt.connector
164
+ .connect()
165
+ .then((apiItems) => {
166
+ let apiItem = apiItems && apiItems[opt.name];
167
+ if (apiItem) {
168
+ apiItem = [...apiItem];
169
+ let url = apiItem.shift();
170
+ if (apiItem.length) {
171
+ const replaceParams = {};
172
+ for (let fry = 0; fry < apiItem.length; fry++) {
173
+ const arg = apiItem[fry];
174
+ replaceParams[fry] = '{' + arg + '}';
175
+ if (params[arg] === undefined) {
176
+ throw new Error('`' + arg + '`' + ' url api argument is not specified');
177
+ }
178
+ }
179
+ if (url) {
180
+ url = template(url, replaceParams);
181
+ }
182
+ }
183
+ // Transfer part of the parameters from `params` to the URL string
184
+ if (params) {
185
+ const paramArray = [];
186
+ const paramList = params.paramList;
187
+ if (Array.isArray(paramList)) {
188
+ delete params.paramList;
189
+ paramList.forEach((x) => {
190
+ paramArray.push(`${x[0]}=${x[1]}`);
191
+ });
192
+ }
193
+ for (const p in params) {
194
+ if (apiItem.indexOf(p) === -1) {
195
+ paramArray.push(`${p}=${params[p]}`);
196
+ }
197
+ }
198
+ if (paramArray.length) {
199
+ url = url + '?' + paramArray.join('&');
200
+ }
201
+ }
202
+ if (url) {
203
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
204
+ }
205
+ else {
206
+ reject(new Error('request url is not set'));
207
+ }
208
+ }
209
+ else {
210
+ resolve(undefined);
211
+ }
212
+ })
213
+ .catch((er) => {
214
+ reject(er);
215
+ });
216
+ });
314
217
  }
315
218
 
316
- /**
317
- * Thrown when ...
318
- */
319
- var ResourceNotFoundError = /** @class */ (function (_super) {
320
- __extends(ResourceNotFoundError, _super);
321
- function ResourceNotFoundError(obj) {
322
- var _this = _super.call(this, obj) || this;
323
- _this.name = 'ResourceNotFoundError';
324
- _this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
325
- Object.setPrototypeOf(_this, ResourceNotFoundError.prototype);
326
- return _this;
327
- }
328
- return ResourceNotFoundError;
329
- }(NgwError));
219
+ /**
220
+ * Thrown when ...
221
+ */
222
+ class ResourceNotFoundError extends NgwError {
223
+ constructor(obj) {
224
+ super(obj);
225
+ this.name = 'ResourceNotFoundError';
226
+ this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
227
+ Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
228
+ }
229
+ }
330
230
 
331
- /**
332
- * Thrown when ...
333
- */
334
- var InsufficientPermissionsError = /** @class */ (function (_super) {
335
- __extends(InsufficientPermissionsError, _super);
336
- function InsufficientPermissionsError(obj) {
337
- var _this = _super.call(this, obj) || this;
338
- _this.name = 'InsufficientPermissionsError';
339
- _this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
340
- Object.setPrototypeOf(_this, InsufficientPermissionsError.prototype);
341
- return _this;
342
- }
343
- return InsufficientPermissionsError;
344
- }(NgwError));
231
+ /**
232
+ * Thrown when ...
233
+ */
234
+ class InsufficientPermissionsError extends NgwError {
235
+ constructor(obj) {
236
+ super(obj);
237
+ this.name = 'InsufficientPermissionsError';
238
+ this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
239
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
240
+ }
241
+ }
345
242
 
346
- var CONNECTORS = [];
347
- function addConnector(connector) {
348
- CONNECTORS.push(connector);
349
- }
350
- function findConnector(options) {
351
- return CONNECTORS.find(function (x) {
352
- if (x.options.baseUrl === options.baseUrl) {
353
- if (options.auth) {
354
- if (x.options.auth) {
355
- return objectDeepEqual(x.options.auth, options.auth);
356
- }
357
- }
358
- else {
359
- // if auth not in find options; use first connector with same url
360
- return true;
361
- }
362
- }
363
- });
364
- }
365
- function removeConnector(connector) {
366
- var index = CONNECTORS.indexOf(connector);
367
- if (index !== -1) {
368
- CONNECTORS.splice(index, 1);
369
- }
243
+ const CONNECTORS = [];
244
+ function addConnector(connector) {
245
+ CONNECTORS.push(connector);
246
+ }
247
+ function findConnector(options) {
248
+ return CONNECTORS.find((x) => {
249
+ if (x.options.baseUrl === options.baseUrl) {
250
+ if (options.auth) {
251
+ if (x.options.auth) {
252
+ return objectDeepEqual(x.options.auth, options.auth);
253
+ }
254
+ }
255
+ else {
256
+ // if auth not in find options; use first connector with same url
257
+ return true;
258
+ }
259
+ }
260
+ });
261
+ }
262
+ function removeConnector(connector) {
263
+ const index = CONNECTORS.indexOf(connector);
264
+ if (index !== -1) {
265
+ CONNECTORS.splice(index, 1);
266
+ }
370
267
  }
371
268
 
372
- var exclude = ['description'];
373
- /**
374
- * @remarks
375
- * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
376
- *
377
- * ```
378
- * { keyname, owner_user: { id }} > { keyname, owner_user__id }
379
- * ```
380
- *
381
- * @param resource - Any property from NGW resource item
382
- */
383
- function resourceToQuery(resource, prefix) {
384
- if (prefix === void 0) { prefix = ''; }
385
- prefix = prefix ? prefix + '__' : '';
386
- var query = {};
387
- for (var _i = 0, _a = Object.entries(resource); _i < _a.length; _i++) {
388
- var _b = _a[_i], key = _b[0], value = _b[1];
389
- if (exclude.indexOf(key) === -1) {
390
- if (isObject(value)) {
391
- if (key === 'owner_user') {
392
- var children = resourceToQuery(value, key);
393
- Object.assign(query, children);
394
- }
395
- else if (key === 'parent' && 'id' in value) {
396
- query.parent_id = value.id;
397
- }
398
- }
399
- else if (defined(value)) {
400
- query[prefix + key] = value;
401
- }
402
- }
403
- }
404
- return query;
269
+ const exclude = ['description'];
270
+ /**
271
+ * @remarks
272
+ * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
273
+ *
274
+ * ```
275
+ * { keyname, owner_user: { id }} > { keyname, owner_user__id }
276
+ * ```
277
+ *
278
+ * @param resource - Any property from NGW resource item
279
+ */
280
+ function resourceToQuery(resource, prefix = '') {
281
+ prefix = prefix ? prefix + '__' : '';
282
+ const query = {};
283
+ for (const [key, value] of Object.entries(resource)) {
284
+ if (exclude.indexOf(key) === -1) {
285
+ if (isObject(value)) {
286
+ if (key === 'owner_user') {
287
+ const children = resourceToQuery(value, key);
288
+ Object.assign(query, children);
289
+ }
290
+ else if (key === 'parent' && 'id' in value) {
291
+ query.parent_id = value.id;
292
+ }
293
+ }
294
+ else if (defined(value)) {
295
+ query[prefix + key] = value;
296
+ }
297
+ }
298
+ }
299
+ return query;
405
300
  }
406
301
 
407
- function resourceCompare(res1, res2) {
408
- return objectDeepEqual(res1, res2);
302
+ function resourceCompare(res1, res2) {
303
+ return objectDeepEqual(res1, res2);
409
304
  }
410
305
 
411
- var ResourcesControl = /** @class */ (function () {
412
- function ResourcesControl(connector) {
413
- this.connector = connector;
414
- this.cache = new Cache();
415
- }
416
- // -------------------------------------------------------------------------
417
- // Resource Methods
418
- // -------------------------------------------------------------------------
419
- /**
420
- * Receive resource from NGW by id, keyname or search-object parameter.
421
- * @param resource - Resource id, keyname or search-object
422
- *
423
- * @remarks
424
- * Fetching resource would be cached to speed up next call
425
- */
426
- ResourcesControl.prototype.getOne = function (resource, requestOptions) {
427
- var _this = this;
428
- var cache = new Cache();
429
- var forCache = {};
430
- var opt = __assign(__assign({}, requestOptions), { cache: false });
431
- if (typeof resource === 'string') {
432
- forCache.keyname = resource;
433
- }
434
- else if (typeof resource === 'number') {
435
- forCache.id = resource;
436
- }
437
- else if (isObject(resource)) {
438
- if (resource.id !== undefined) {
439
- forCache.id = resource.id;
440
- }
441
- else if (resource.keyname) {
442
- forCache.keyname = resource.keyname;
443
- }
444
- }
445
- var makeRequest = function () {
446
- if (typeof resource === 'string') {
447
- return _this._fetchResourceBy({ keyname: resource }, opt);
448
- }
449
- else if (typeof resource === 'number') {
450
- return _this._fetchResourceById(resource, opt);
451
- }
452
- else if (isObject(resource)) {
453
- return _this._fetchResourceBy(resource, opt);
454
- }
455
- return CancelablePromise.resolve(undefined);
456
- };
457
- return cache.addFull('resource', makeRequest, forCache);
458
- };
459
- ResourcesControl.prototype.getOneOrFail = function (resource, requestOptions) {
460
- return this.getOne(resource, requestOptions).then(function (res) {
461
- if (res) {
462
- return res;
463
- }
464
- throw new ResourceNotFoundError();
465
- });
466
- };
467
- /**
468
- * A fast way to retrieve resource ID for any resource definition.
469
- * @param resource - Any available resource definition
470
- *
471
- * @remarks
472
- * There are situations when exactly the resource id is needed
473
- * (for example, to compose the correct request to the api)
474
- * then this method will come in handy to facilitate the extraction of the identifier
475
- * if the resource is specified through a keyname or other parameters.
476
- */
477
- ResourcesControl.prototype.getId = function (resource, requestOptions) {
478
- if (typeof resource === 'number') {
479
- return CancelablePromise.resolve(resource);
480
- }
481
- else if (typeof resource === 'string' || isObject(resource)) {
482
- return this.getOne(resource, requestOptions).then(function (res) {
483
- if (res) {
484
- return res.resource.id;
485
- }
486
- });
487
- }
488
- return CancelablePromise.resolve(undefined);
489
- };
490
- /**
491
- * A fast way to retrieve resource ID for any resource definition.
492
- * @param resource - Any available resource definition
493
- *
494
- * @remarks
495
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
496
- * To not make one more checks if the resource is definitely exists
497
- */
498
- ResourcesControl.prototype.getIdOrFail = function (resource, requestOptions) {
499
- return this.getId(resource, requestOptions).then(function (resp) {
500
- if (resp === undefined) {
501
- throw new Error();
502
- }
503
- return resp;
504
- });
505
- };
506
- ResourcesControl.prototype.getMany = function (resource, requestOptions) {
507
- var _this = this;
508
- return this._resourceCacheFilter(resource).then(function (items) {
509
- if (!items.length) {
510
- var query = {};
511
- if (resource.keyname) {
512
- query.keyname = resource.keyname;
513
- }
514
- else {
515
- Object.assign(query, resourceToQuery(resource));
516
- }
517
- return _this.connector
518
- .get('resource.search', requestOptions, __assign({ serialization: 'full' }, query))
519
- .then(function (resources) {
520
- if (resources) {
521
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
522
- var x = resources_1[_i];
523
- _this.cache.add('resource.item', CancelablePromise.resolve(x), {
524
- id: x.resource.id,
525
- });
526
- }
527
- }
528
- return resources;
529
- });
530
- }
531
- return items;
532
- });
533
- };
534
- ResourcesControl.prototype.getParent = function (resource, requestOptions) {
535
- var _this = this;
536
- return this.getOne(resource, requestOptions).then(function (child) {
537
- if (child) {
538
- return _this.getOne(child.resource.parent.id, requestOptions);
539
- }
540
- return CancelablePromise.resolve(undefined);
541
- });
542
- };
543
- ResourcesControl.prototype.getChildrenOf = function (resource, requestOptions) {
544
- var _this = this;
545
- return this.getIdOrFail(resource).then(function (parent) {
546
- return _this._getChildrenOf(parent, requestOptions);
547
- });
548
- };
549
- ResourcesControl.prototype.update = function (resource, data) {
550
- var _this = this;
551
- return this.getId(resource).then(function (id) {
552
- if (id !== undefined) {
553
- return _this.connector.put('resource.item', { data: data }, { id: id });
554
- }
555
- });
556
- };
557
- /**
558
- * Fast way to delete resource from NGW and clean cache.
559
- * @param resource - Resource definition
560
- */
561
- ResourcesControl.prototype.delete = function (resource) {
562
- var _this = this;
563
- return this.getId(resource).then(function (id) {
564
- if (id !== undefined) {
565
- return _this.connector.delete('resource.item', null, { id: id }).then(function () {
566
- _this._cleanResourceItemCache(id);
567
- return undefined;
568
- });
569
- }
570
- });
571
- };
572
- ResourcesControl.prototype._getChildrenOf = function (parent, requestOptions, _items) {
573
- var _this = this;
574
- if (_items === void 0) { _items = []; }
575
- return this.connector
576
- .get('resource.collection', __assign({ cache: true }, requestOptions), {
577
- parent: parent,
578
- })
579
- .then(function (items) {
580
- var recursivePromises = [];
581
- for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
582
- var item = items_1[_i];
583
- _this.cache.add('resource.item', CancelablePromise.resolve(item), {
584
- id: item.resource.id,
585
- });
586
- _items.push(item);
587
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
588
- recursivePromises.push(_this._getChildrenOf(item.resource.id, requestOptions, _items));
589
- }
590
- }
591
- if (recursivePromises.length) {
592
- return CancelablePromise.all(recursivePromises).then(function () {
593
- return _items;
594
- });
595
- }
596
- return _items;
597
- });
598
- };
599
- ResourcesControl.prototype._cleanResourceItemCache = function (id) {
600
- return __awaiter(this, void 0, void 0, function () {
601
- var all, toDelete, _i, all_1, c, cid, rid, _a, toDelete_1, d;
602
- return __generator(this, function (_b) {
603
- switch (_b.label) {
604
- case 0:
605
- all = this.cache.all();
606
- toDelete = [];
607
- _i = 0, all_1 = all;
608
- _b.label = 1;
609
- case 1:
610
- if (!(_i < all_1.length)) return [3 /*break*/, 5];
611
- c = all_1[_i];
612
- cid = c.options && c.options.id;
613
- if (!(['resource.item', 'resource'].includes(c.key) && cid !== undefined)) return [3 /*break*/, 4];
614
- if (!(typeof cid === 'number')) return [3 /*break*/, 2];
615
- if (cid === id) {
616
- toDelete.push(c);
617
- }
618
- return [3 /*break*/, 4];
619
- case 2: return [4 /*yield*/, this.getId(cid)];
620
- case 3:
621
- rid = _b.sent();
622
- if (rid === id) {
623
- toDelete.push(c);
624
- }
625
- _b.label = 4;
626
- case 4:
627
- _i++;
628
- return [3 /*break*/, 1];
629
- case 5:
630
- for (_a = 0, toDelete_1 = toDelete; _a < toDelete_1.length; _a++) {
631
- d = toDelete_1[_a];
632
- this.cache.delete(d);
633
- }
634
- return [2 /*return*/];
635
- }
636
- });
637
- });
638
- };
639
- ResourcesControl.prototype._fetchResourceById = function (id, requestOptions) {
640
- var _this = this;
641
- var promise = function () {
642
- return _this.connector.get('resource.item', requestOptions, { id: id });
643
- };
644
- return this.cache
645
- .add('resource.item', promise, {
646
- id: id,
647
- })
648
- .catch(function (er) {
649
- if (!(er instanceof ResourceNotFoundError)) {
650
- throw er;
651
- }
652
- return undefined;
653
- });
654
- };
655
- ResourcesControl.prototype._fetchResourceBy = function (resource, requestOptions) {
656
- return this.getMany(resource, requestOptions).then(function (resources) {
657
- return resources[0];
658
- });
659
- };
660
- ResourcesControl.prototype._resourceCacheFilter = function (resource) {
661
- return CancelablePromise.all(this.cache.matchAll('resource.item')).then(function (resources) {
662
- var items = [];
663
- resources.filter(function (x) {
664
- if (x) {
665
- // identical by uniq props
666
- if (resource.keyname && x.resource.keyname) {
667
- return resource.keyname === x.resource.keyname;
668
- }
669
- if (defined(resource.id) && defined(x.resource.id)) {
670
- return resource.id === x.resource.id;
671
- }
672
- return resourceCompare(resource, x.resource);
673
- }
674
- });
675
- return items;
676
- });
677
- };
678
- return ResourcesControl;
679
- }());
306
+ class ResourcesControl {
307
+ constructor(connector) {
308
+ this.connector = connector;
309
+ this.cache = new Cache();
310
+ }
311
+ // -------------------------------------------------------------------------
312
+ // Resource Methods
313
+ // -------------------------------------------------------------------------
314
+ /**
315
+ * Receive resource from NGW by id, keyname or search-object parameter.
316
+ * @param resource - Resource id, keyname or search-object
317
+ *
318
+ * @remarks
319
+ * Fetching resource would be cached to speed up next call
320
+ */
321
+ getOne(resource, requestOptions) {
322
+ const cache = new Cache();
323
+ const forCache = {};
324
+ const opt = { ...requestOptions, cache: false };
325
+ if (typeof resource === 'string') {
326
+ forCache.keyname = resource;
327
+ }
328
+ else if (typeof resource === 'number') {
329
+ forCache.id = resource;
330
+ }
331
+ else if (isObject(resource)) {
332
+ if (resource.id !== undefined) {
333
+ forCache.id = resource.id;
334
+ }
335
+ else if (resource.keyname) {
336
+ forCache.keyname = resource.keyname;
337
+ }
338
+ }
339
+ const makeRequest = () => {
340
+ if (typeof resource === 'string') {
341
+ return this._fetchResourceBy({ keyname: resource }, opt);
342
+ }
343
+ else if (typeof resource === 'number') {
344
+ return this._fetchResourceById(resource, opt);
345
+ }
346
+ else if (isObject(resource)) {
347
+ return this._fetchResourceBy(resource, opt);
348
+ }
349
+ return CancelablePromise.resolve(undefined);
350
+ };
351
+ return cache.addFull('resource', makeRequest, forCache);
352
+ }
353
+ getOneOrFail(resource, requestOptions) {
354
+ return this.getOne(resource, requestOptions).then((res) => {
355
+ if (res) {
356
+ return res;
357
+ }
358
+ throw new ResourceNotFoundError();
359
+ });
360
+ }
361
+ /**
362
+ * A fast way to retrieve resource ID for any resource definition.
363
+ * @param resource - Any available resource definition
364
+ *
365
+ * @remarks
366
+ * There are situations when exactly the resource id is needed
367
+ * (for example, to compose the correct request to the api)
368
+ * then this method will come in handy to facilitate the extraction of the identifier
369
+ * if the resource is specified through a keyname or other parameters.
370
+ */
371
+ getId(resource, requestOptions) {
372
+ if (typeof resource === 'number') {
373
+ return CancelablePromise.resolve(resource);
374
+ }
375
+ else if (typeof resource === 'string' || isObject(resource)) {
376
+ return this.getOne(resource, requestOptions).then((res) => {
377
+ if (res) {
378
+ return res.resource.id;
379
+ }
380
+ });
381
+ }
382
+ return CancelablePromise.resolve(undefined);
383
+ }
384
+ /**
385
+ * A fast way to retrieve resource ID for any resource definition.
386
+ * @param resource - Any available resource definition
387
+ *
388
+ * @remarks
389
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
390
+ * To not make one more checks if the resource is definitely exists
391
+ */
392
+ getIdOrFail(resource, requestOptions) {
393
+ return this.getId(resource, requestOptions).then((resp) => {
394
+ if (resp === undefined) {
395
+ throw new Error();
396
+ }
397
+ return resp;
398
+ });
399
+ }
400
+ getMany(resource, requestOptions) {
401
+ return this._resourceCacheFilter(resource).then((items) => {
402
+ if (!items.length) {
403
+ const query = {};
404
+ if (resource.keyname) {
405
+ query.keyname = resource.keyname;
406
+ }
407
+ else {
408
+ Object.assign(query, resourceToQuery(resource));
409
+ }
410
+ return this.connector
411
+ .get('resource.search', requestOptions, {
412
+ serialization: 'full',
413
+ ...query,
414
+ })
415
+ .then((resources) => {
416
+ if (resources) {
417
+ for (const x of resources) {
418
+ this.cache.add('resource.item', CancelablePromise.resolve(x), {
419
+ id: x.resource.id,
420
+ });
421
+ }
422
+ }
423
+ return resources;
424
+ });
425
+ }
426
+ return items;
427
+ });
428
+ }
429
+ getParent(resource, requestOptions) {
430
+ return this.getOne(resource, requestOptions).then((child) => {
431
+ if (child) {
432
+ return this.getOne(child.resource.parent.id, requestOptions);
433
+ }
434
+ return CancelablePromise.resolve(undefined);
435
+ });
436
+ }
437
+ getChildrenOf(resource, requestOptions) {
438
+ return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
439
+ }
440
+ update(resource, data) {
441
+ return this.getId(resource).then((id) => {
442
+ if (id !== undefined) {
443
+ return this.connector.put('resource.item', { data }, { id });
444
+ }
445
+ });
446
+ }
447
+ /**
448
+ * Fast way to delete resource from NGW and clean cache.
449
+ * @param resource - Resource definition
450
+ */
451
+ delete(resource) {
452
+ return this.getId(resource).then((id) => {
453
+ if (id !== undefined) {
454
+ return this.connector.delete('resource.item', null, { id }).then(() => {
455
+ this._cleanResourceItemCache(id);
456
+ return undefined;
457
+ });
458
+ }
459
+ });
460
+ }
461
+ _getChildrenOf(parent, requestOptions, _items = []) {
462
+ return this.connector
463
+ .get('resource.collection', { cache: true, ...requestOptions }, {
464
+ parent,
465
+ })
466
+ .then((items) => {
467
+ const recursivePromises = [];
468
+ for (const item of items) {
469
+ this.cache.add('resource.item', CancelablePromise.resolve(item), {
470
+ id: item.resource.id,
471
+ });
472
+ _items.push(item);
473
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
474
+ recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
475
+ }
476
+ }
477
+ if (recursivePromises.length) {
478
+ return CancelablePromise.all(recursivePromises).then(() => {
479
+ return _items;
480
+ });
481
+ }
482
+ return _items;
483
+ });
484
+ }
485
+ async _cleanResourceItemCache(id) {
486
+ const all = this.cache.all();
487
+ const toDelete = [];
488
+ for (const c of all) {
489
+ const cid = c.options && c.options.id;
490
+ if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
491
+ if (typeof cid === 'number') {
492
+ if (cid === id) {
493
+ toDelete.push(c);
494
+ }
495
+ }
496
+ else {
497
+ const rid = await this.getId(cid);
498
+ if (rid === id) {
499
+ toDelete.push(c);
500
+ }
501
+ }
502
+ }
503
+ }
504
+ for (const d of toDelete) {
505
+ this.cache.delete(d);
506
+ }
507
+ }
508
+ _fetchResourceById(id, requestOptions) {
509
+ const promise = () => this.connector.get('resource.item', requestOptions, { id });
510
+ return this.cache
511
+ .add('resource.item', promise, {
512
+ id,
513
+ })
514
+ .catch((er) => {
515
+ if (!(er instanceof ResourceNotFoundError)) {
516
+ throw er;
517
+ }
518
+ return undefined;
519
+ });
520
+ }
521
+ _fetchResourceBy(resource, requestOptions) {
522
+ return this.getMany(resource, requestOptions).then((resources) => {
523
+ return resources[0];
524
+ });
525
+ }
526
+ _resourceCacheFilter(resource) {
527
+ return CancelablePromise.all(this.cache.matchAll('resource.item')).then((resources) => {
528
+ const items = [];
529
+ resources.filter((x) => {
530
+ if (x) {
531
+ // identical by uniq props
532
+ if (resource.keyname && x.resource.keyname) {
533
+ return resource.keyname === x.resource.keyname;
534
+ }
535
+ if (defined(resource.id) && defined(x.resource.id)) {
536
+ return resource.id === x.resource.id;
537
+ }
538
+ return resourceCompare(resource, x.resource);
539
+ }
540
+ });
541
+ return items;
542
+ });
543
+ }
544
+ }
680
545
 
681
- var ID = 0;
682
- var NgwConnector$1 = /** @class */ (function () {
683
- function NgwConnector(options) {
684
- this.options = options;
685
- this.id = ID++;
686
- this.emitter = new EventEmitter();
687
- this.routeStr = '/api/component/pyramid/route';
688
- this.activeRequests = [];
689
- var exist = findConnector(options);
690
- if (exist) {
691
- return exist;
692
- }
693
- else {
694
- if (this.options.route) {
695
- this.routeStr = this.options.route;
696
- }
697
- if (this.options.requestTransform) {
698
- this.requestTransform = this.options.requestTransform;
699
- }
700
- this.resources = new ResourcesControl(this);
701
- addConnector(this);
702
- }
703
- }
704
- NgwConnector.create = function (options) {
705
- return new this(options);
706
- };
707
- NgwConnector.prototype.setRequestTransform = function (requestTransform) {
708
- this.requestTransform = requestTransform;
709
- };
710
- /**
711
- * Fast way to specify the connection address to NextGIS Web.
712
- * The current connection will be severed.
713
- * @param baseUrl - NGW url
714
- */
715
- NgwConnector.prototype.setNgw = function (baseUrl) {
716
- this.logout();
717
- this.options.baseUrl = baseUrl;
718
- addConnector(this);
719
- };
720
- /**
721
- * Establishing a connection with NextGIS Web to fulfill all other requests.
722
- * @remarks
723
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
724
- * Can be used to check connection.
725
- * @example
726
- * ```javascript
727
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
728
- * connector.connect()
729
- * .then(() => console.log('Ok'))
730
- * .catch((er) => console.log('Connection problem', er));
731
- * ```
732
- */
733
- NgwConnector.prototype.connect = function () {
734
- var _this = this;
735
- var cache = new Cache();
736
- var auth = this.options.auth;
737
- var makeConnect = function () {
738
- return new CancelablePromise(function (resolve, reject) {
739
- var makeQuery = function () {
740
- return _this.makeQuery(_this.routeStr, {}, {})
741
- .then(function (route) {
742
- resolve(route);
743
- })
744
- .catch(function (er) {
745
- reject(er);
746
- });
747
- };
748
- if (auth) {
749
- var login = auth.login, password = auth.password;
750
- if (login && password) {
751
- return _this._login({ login: login, password: password })
752
- .then(function () {
753
- return makeQuery();
754
- })
755
- .catch(function (er) { return reject(er); });
756
- }
757
- }
758
- return makeQuery();
759
- });
760
- };
761
- return cache.add('route', makeConnect, {
762
- id: this.id,
763
- auth: auth,
764
- baseUrl: this.options.baseUrl,
765
- });
766
- };
767
- /**
768
- * Quick way to change NextGIS Web user.
769
- * @param credentials - New user credentials
770
- */
771
- NgwConnector.prototype.login = function (credentials, options) {
772
- this.logout();
773
- addConnector(this);
774
- return this._login(credentials, options);
775
- };
776
- /**
777
- * Disconnecting a user. Aborting all current requests
778
- */
779
- NgwConnector.prototype.logout = function () {
780
- this.abort();
781
- removeConnector(this);
782
- this.options.auth = undefined;
783
- this.user = undefined;
784
- this.emitter.emit('logout');
785
- this.resources.cache.clean();
786
- };
787
- NgwConnector.prototype.getUserInfo = function (credentials, options) {
788
- if (this.user && this.user.id) {
789
- return CancelablePromise.resolve(this.user);
790
- }
791
- if (credentials) {
792
- this.options.auth = credentials;
793
- }
794
- var options_ = __assign({ headers: this.getAuthorizationHeaders(credentials) }, options);
795
- // Do not use apiRequest('auth.current_user') to avoid circular-references
796
- return this.makeQuery('/api/component/auth/current_user', {}, options_);
797
- };
798
- /**
799
- * Obtaining the required Headers for authentication of requests in the NGW.
800
- */
801
- NgwConnector.prototype.getAuthorizationHeaders = function (credentials) {
802
- var client = this.makeClientId(credentials);
803
- if (client) {
804
- return {
805
- Authorization: 'Basic ' + client,
806
- };
807
- }
808
- };
809
- NgwConnector.prototype.makeClientId = function (credentials) {
810
- credentials = credentials || this.options.auth;
811
- if (credentials) {
812
- var login = credentials.login, password = credentials.password;
813
- var str = unescape(encodeURIComponent("".concat(login, ":").concat(password)));
814
- // @ts-ignore
815
- {
816
- return window.btoa(str);
817
- }
818
- }
819
- };
820
- /** Stop all api requests */
821
- NgwConnector.prototype.abort = function () {
822
- for (var _i = 0, _a = this.activeRequests; _i < _a.length; _i++) {
823
- var req = _a[_i];
824
- req.cancel();
825
- }
826
- this.activeRequests = [];
827
- };
828
- NgwConnector.prototype.getActiveApiRequests = function () {
829
- return __spreadArray([], this.activeRequests, true);
830
- };
831
- /**
832
- * Send request to NGW api router.
833
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
834
- * @param params - Request item params or query params
835
- * @param requestOptions - Request options
836
- *
837
- * @example
838
- * ```javascript
839
- *
840
- * // there is such an NGW route item
841
- * // "feature_layer.feature.item": [
842
- * // "/api/resource/{0}/feature/{1}",
843
- * // "id",
844
- * // "fid"
845
- * // ],
846
- *
847
- * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
848
- * connector.apiRequest('feature_layer.feature.item', {
849
- * // request params for {0} and {1}
850
- * 'id': 2011,
851
- * 'fid': 101,
852
- * // query params
853
- * 'srs': 4326,
854
- * 'geom_format': 'geojson',
855
- * }, { method: 'GET' });
856
- * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
857
- *
858
- * ```
859
- */
860
- NgwConnector.prototype.apiRequest = function (name, params_, requestOptions) {
861
- var _this = this;
862
- var _a;
863
- if (params_ === void 0) { params_ = {}; }
864
- if (requestOptions === void 0) { requestOptions = {}; }
865
- var method = requestOptions.method, headers = requestOptions.headers, withCredentials = requestOptions.withCredentials, responseType = requestOptions.responseType;
866
- var params = objectRemoveEmpty(params_);
867
- var makeApiRequest = function () {
868
- return apiRequest({ name: name, params: params, requestOptions: requestOptions, connector: _this });
869
- };
870
- if (requestOptions.cache && method === 'GET') {
871
- var cache = new Cache();
872
- return cache.add(name, makeApiRequest, __assign({ params: params }, objectRemoveEmpty({
873
- headers: headers,
874
- withCredentials: withCredentials,
875
- responseType: responseType,
876
- baseUrl: this.options.baseUrl,
877
- userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
878
- })));
879
- }
880
- return makeApiRequest();
881
- };
882
- /**
883
- * Shortcut method for send POST request to NGW.
884
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
885
- * @param options - Request options
886
- * @param params - Request item params or query params
887
- *
888
- * @example
889
- * ```javascript
890
- * connector.post('resource.collection', { data: POST_PAYLOAD })
891
- * .then((newResource) => console.log(newResource))
892
- * .catch((error) => console.warn(error));
893
- * ```
894
- */
895
- NgwConnector.prototype.post = function (name, options, params) {
896
- options = options || {};
897
- options.method = 'POST';
898
- return this.apiRequest(name, params, options);
899
- };
900
- /**
901
- * Shortcut method for send GET request to NGW.
902
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
903
- * @param options - Request options
904
- * @param params - Request item params or query params
905
- */
906
- NgwConnector.prototype.get = function (name, options, params) {
907
- options = options || {};
908
- options.method = 'GET';
909
- return this.apiRequest(name, params, options);
910
- };
911
- /**
912
- * Shortcut method for send PATCH request to NGW.
913
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
914
- * @param options - Request options
915
- * @param params - Request item params or query params
916
- */
917
- NgwConnector.prototype.patch = function (name, options, params) {
918
- options = options || {};
919
- options.method = 'PATCH';
920
- return this.apiRequest(name, params, options);
921
- };
922
- /**
923
- * Shortcut method for send PUT request to NGW.
924
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
925
- * @param options - Request options
926
- * @param params - Request item params or query params
927
- */
928
- NgwConnector.prototype.put = function (name, options, params) {
929
- options = options || {};
930
- options.method = 'PUT';
931
- return this.apiRequest(name, params, options);
932
- };
933
- /**
934
- * Shortcut method for send DELETE request to NGW.
935
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
936
- * @param options - Request options
937
- * @param params - Request item params or query params
938
- */
939
- NgwConnector.prototype.delete = function (name, options, params) {
940
- options = options || {};
941
- options.method = 'DELETE';
942
- return this.apiRequest(name, params, options);
943
- };
944
- /**
945
- * Send request to NGW.
946
- * @param url - URL address to NGW
947
- * @param params - Query params
948
- * @param options - Request options
949
- */
950
- NgwConnector.prototype.makeQuery = function (url, params, options) {
951
- if (options === void 0) { options = {}; }
952
- url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
953
- if (url) {
954
- if (params) {
955
- url = template(url, params);
956
- }
957
- url = encodeURI(fixUrlStr(url));
958
- return this._loadData(url, options);
959
- }
960
- else {
961
- throw new Error('Empty `url` not allowed');
962
- }
963
- };
964
- // -------------------------------------------------------------------------
965
- // Resource Methods
966
- // -------------------------------------------------------------------------
967
- /**
968
- * {@link ResourcesControl.getOne}
969
- */
970
- NgwConnector.prototype.getResource = function (resource, requestOptions) {
971
- return this.resources.getOne(resource, requestOptions);
972
- };
973
- /**
974
- * {@link ResourcesControl.getOneOrFail}
975
- */
976
- NgwConnector.prototype.getResourceOrFail = function (resource, requestOptions) {
977
- return this.resources.getOneOrFail(resource, requestOptions);
978
- };
979
- /**
980
- * @deprecated - use {@link getResource}
981
- */
982
- NgwConnector.prototype.getResourceBy = function (resource) {
983
- return this.resources.getOne(resource);
984
- };
985
- /**
986
- * @deprecated - use {@link getResource}
987
- */
988
- NgwConnector.prototype.getResourceByKeyname = function (keyname) {
989
- return this.resources.getOne(keyname);
990
- };
991
- /**
992
- * @deprecated - use {@link getResource}
993
- */
994
- NgwConnector.prototype.getResourceById = function (id) {
995
- return this.resources.getOne(id);
996
- };
997
- /**
998
- * {@link ResourcesControl.getId}
999
- */
1000
- NgwConnector.prototype.getResourceId = function (resource, requestOptions) {
1001
- return this.resources.getId(resource, requestOptions);
1002
- };
1003
- /**
1004
- * {@link ResourcesControl.getIdOrFail}
1005
- */
1006
- NgwConnector.prototype.getResourceIdOrFail = function (resource, requestOptions) {
1007
- return this.resources.getIdOrFail(resource, requestOptions);
1008
- };
1009
- /**
1010
- * {@link ResourcesControl.getMany}
1011
- */
1012
- NgwConnector.prototype.getResourcesBy = function (resource, requestOptions) {
1013
- return this.resources.getMany(resource, requestOptions);
1014
- };
1015
- /**
1016
- * {@link ResourcesControl.getParent}
1017
- */
1018
- NgwConnector.prototype.getResourceParent = function (resource, requestOptions) {
1019
- return this.resources.getParent(resource, requestOptions);
1020
- };
1021
- /**
1022
- * {@link ResourcesControl.getChildrenOf}
1023
- */
1024
- NgwConnector.prototype.getResourceChildren = function (resource, requestOptions) {
1025
- return this.resources.getChildrenOf(resource, requestOptions);
1026
- };
1027
- /**
1028
- * {@link ResourcesControl.update}
1029
- */
1030
- NgwConnector.prototype.updateResource = function (resource, data) {
1031
- return this.resources.update(resource, data);
1032
- };
1033
- /**
1034
- * {@link ResourcesControl.delete}
1035
- */
1036
- NgwConnector.prototype.deleteResource = function (resource) {
1037
- return this.resources.delete(resource);
1038
- };
1039
- /**
1040
- * @internal
1041
- */
1042
- NgwConnector.prototype._loadData = function (url, options) {
1043
- var _this = this;
1044
- options.responseType = options.responseType || 'json';
1045
- var request = new CancelablePromise(function (resolve, reject, onCancel) {
1046
- if (_this.user) {
1047
- options = options || {};
1048
- // options.withCredentials = true;
1049
- options.headers = __assign(__assign({}, _this.getAuthorizationHeaders()), options.headers);
1050
- }
1051
- if (_this.requestTransform) {
1052
- var _a = _this.requestTransform(url, options), transUrl = _a[0], transOptions = _a[1];
1053
- url = transUrl;
1054
- options = transOptions;
1055
- }
1056
- loadData(url, resolve, options, reject, onCancel);
1057
- })
1058
- .then(function (resp) {
1059
- _this._cleanActiveRequests(request);
1060
- return resp;
1061
- })
1062
- .catch(function (httpError) {
1063
- _this._cleanActiveRequests(request);
1064
- if (httpError instanceof CancelablePromise.CancelError) ;
1065
- else {
1066
- // @ts-ignore
1067
- if ((process.env.NODE_ENV !== 'production')) {
1068
- console.warn('DEV WARN', httpError);
1069
- }
1070
- var er = _this._handleHttpError(httpError);
1071
- if (er) {
1072
- throw er;
1073
- }
1074
- }
1075
- });
1076
- if (options.signal &&
1077
- typeof options.signal.addEventListener === 'function') {
1078
- options.signal.addEventListener('abort', function () {
1079
- request.cancel();
1080
- _this._cleanActiveRequests(request);
1081
- });
1082
- }
1083
- this.activeRequests.push(request);
1084
- return request;
1085
- };
1086
- NgwConnector.prototype._login = function (credentials, options) {
1087
- var _this = this;
1088
- return this.getUserInfo(credentials, options)
1089
- .then(function (data) {
1090
- _this.user = data;
1091
- _this.emitter.emit('login', data);
1092
- return data;
1093
- })
1094
- .catch(function (er) {
1095
- _this.emitter.emit('login:error', er);
1096
- throw er;
1097
- });
1098
- };
1099
- NgwConnector.prototype._cleanActiveRequests = function (request) {
1100
- var activeRequestIndex = this.activeRequests.indexOf(request);
1101
- if (activeRequestIndex !== -1) {
1102
- this.activeRequests.splice(activeRequestIndex, 1);
1103
- }
1104
- };
1105
- NgwConnector.prototype._handleHttpError = function (er) {
1106
- if (er) {
1107
- if (er instanceof NgwError) {
1108
- if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
1109
- throw new ResourceNotFoundError(er);
1110
- }
1111
- else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
1112
- throw new InsufficientPermissionsError(er);
1113
- }
1114
- }
1115
- }
1116
- return er;
1117
- };
1118
- NgwConnector.errors = {
1119
- NgwError: NgwError,
1120
- ResourceNotFoundError: ResourceNotFoundError,
1121
- };
1122
- return NgwConnector;
1123
- }());
546
+ let ID = 0;
547
+ class NgwConnector$1 {
548
+ constructor(options) {
549
+ this.options = options;
550
+ this.id = ID++;
551
+ this.emitter = new EventEmitter();
552
+ this.routeStr = '/api/component/pyramid/route';
553
+ this.activeRequests = [];
554
+ const exist = findConnector(options);
555
+ if (exist) {
556
+ return exist;
557
+ }
558
+ else {
559
+ if (this.options.route) {
560
+ this.routeStr = this.options.route;
561
+ }
562
+ if (this.options.requestTransform) {
563
+ this.requestTransform = this.options.requestTransform;
564
+ }
565
+ this.resources = new ResourcesControl(this);
566
+ addConnector(this);
567
+ }
568
+ }
569
+ static create(options) {
570
+ return new this(options);
571
+ }
572
+ setRequestTransform(requestTransform) {
573
+ this.requestTransform = requestTransform;
574
+ }
575
+ /**
576
+ * Fast way to specify the connection address to NextGIS Web.
577
+ * The current connection will be severed.
578
+ * @param baseUrl - NGW url
579
+ */
580
+ setNgw(baseUrl) {
581
+ this.logout();
582
+ this.options.baseUrl = baseUrl;
583
+ addConnector(this);
584
+ }
585
+ /**
586
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
587
+ * @remarks
588
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
589
+ * Can be used to check connection.
590
+ * @example
591
+ * ```javascript
592
+ * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
593
+ * connector.connect()
594
+ * .then(() => console.log('Ok'))
595
+ * .catch((er) => console.log('Connection problem', er));
596
+ * ```
597
+ */
598
+ connect() {
599
+ const cache = new Cache();
600
+ const auth = this.options.auth;
601
+ const makeConnect = () => new CancelablePromise((resolve, reject) => {
602
+ const makeQuery = () => {
603
+ return this.makeQuery(this.routeStr, {}, {})
604
+ .then((route) => {
605
+ resolve(route);
606
+ })
607
+ .catch((er) => {
608
+ reject(er);
609
+ });
610
+ };
611
+ if (auth) {
612
+ const { login, password } = auth;
613
+ if (login && password) {
614
+ return this._login({ login, password })
615
+ .then(() => {
616
+ return makeQuery();
617
+ })
618
+ .catch((er) => reject(er));
619
+ }
620
+ }
621
+ return makeQuery();
622
+ });
623
+ return cache.add('route', makeConnect, {
624
+ id: this.id,
625
+ auth,
626
+ baseUrl: this.options.baseUrl,
627
+ });
628
+ }
629
+ /**
630
+ * Quick way to change NextGIS Web user.
631
+ * @param credentials - New user credentials
632
+ */
633
+ login(credentials, options) {
634
+ this.logout();
635
+ addConnector(this);
636
+ return this._login(credentials, options);
637
+ }
638
+ /**
639
+ * Disconnecting a user. Aborting all current requests
640
+ */
641
+ logout() {
642
+ this.abort();
643
+ removeConnector(this);
644
+ this.options.auth = undefined;
645
+ this.user = undefined;
646
+ this.emitter.emit('logout');
647
+ this.resources.cache.clean();
648
+ }
649
+ getUserInfo(credentials, options) {
650
+ if (this.user && this.user.id) {
651
+ return CancelablePromise.resolve(this.user);
652
+ }
653
+ if (credentials) {
654
+ this.options.auth = credentials;
655
+ }
656
+ const options_ = {
657
+ headers: this.getAuthorizationHeaders(credentials),
658
+ // withCredentials: true
659
+ ...options,
660
+ };
661
+ // Do not use apiRequest('auth.current_user') to avoid circular-references
662
+ return this.makeQuery('/api/component/auth/current_user', {}, options_);
663
+ }
664
+ /**
665
+ * Obtaining the required Headers for authentication of requests in the NGW.
666
+ */
667
+ getAuthorizationHeaders(credentials) {
668
+ const client = this.makeClientId(credentials);
669
+ if (client) {
670
+ return {
671
+ Authorization: 'Basic ' + client,
672
+ };
673
+ }
674
+ }
675
+ makeClientId(credentials) {
676
+ credentials = credentials || this.options.auth;
677
+ if (credentials) {
678
+ const { login, password } = credentials;
679
+ const str = unescape(encodeURIComponent(`${login}:${password}`));
680
+ // @ts-ignore
681
+ {
682
+ return window.btoa(str);
683
+ }
684
+ }
685
+ }
686
+ /** Stop all api requests */
687
+ abort() {
688
+ for (const req of this.activeRequests) {
689
+ req.cancel();
690
+ }
691
+ this.activeRequests = [];
692
+ }
693
+ getActiveApiRequests() {
694
+ return [...this.activeRequests];
695
+ }
696
+ /**
697
+ * Send request to NGW api router.
698
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
699
+ * @param params - Request item params or query params
700
+ * @param requestOptions - Request options
701
+ *
702
+ * @example
703
+ * ```javascript
704
+ *
705
+ * // there is such an NGW route item
706
+ * // "feature_layer.feature.item": [
707
+ * // "/api/resource/{0}/feature/{1}",
708
+ * // "id",
709
+ * // "fid"
710
+ * // ],
711
+ *
712
+ * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
713
+ * connector.apiRequest('feature_layer.feature.item', {
714
+ * // request params for {0} and {1}
715
+ * 'id': 2011,
716
+ * 'fid': 101,
717
+ * // query params
718
+ * 'srs': 4326,
719
+ * 'geom_format': 'geojson',
720
+ * }, { method: 'GET' });
721
+ * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
722
+ *
723
+ * ```
724
+ */
725
+ apiRequest(name, params_ = {}, requestOptions = {}) {
726
+ var _a;
727
+ const { method, headers, withCredentials, responseType } = requestOptions;
728
+ const params = objectRemoveEmpty(params_);
729
+ const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
730
+ if (requestOptions.cache && method === 'GET') {
731
+ const cache = new Cache();
732
+ return cache.add(name, makeApiRequest, {
733
+ params,
734
+ ...objectRemoveEmpty({
735
+ headers,
736
+ withCredentials,
737
+ responseType,
738
+ baseUrl: this.options.baseUrl,
739
+ userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
740
+ }),
741
+ });
742
+ }
743
+ return makeApiRequest();
744
+ }
745
+ /**
746
+ * Shortcut method for send POST request to NGW.
747
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
748
+ * @param options - Request options
749
+ * @param params - Request item params or query params
750
+ *
751
+ * @example
752
+ * ```javascript
753
+ * connector.post('resource.collection', { data: POST_PAYLOAD })
754
+ * .then((newResource) => console.log(newResource))
755
+ * .catch((error) => console.warn(error));
756
+ * ```
757
+ */
758
+ post(name, options, params) {
759
+ options = options || {};
760
+ options.method = 'POST';
761
+ return this.apiRequest(name, params, options);
762
+ }
763
+ /**
764
+ * Shortcut method for send GET request to NGW.
765
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
766
+ * @param options - Request options
767
+ * @param params - Request item params or query params
768
+ */
769
+ get(name, options, params) {
770
+ options = options || {};
771
+ options.method = 'GET';
772
+ return this.apiRequest(name, params, options);
773
+ }
774
+ /**
775
+ * Shortcut method for send PATCH request to NGW.
776
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
777
+ * @param options - Request options
778
+ * @param params - Request item params or query params
779
+ */
780
+ patch(name, options, params) {
781
+ options = options || {};
782
+ options.method = 'PATCH';
783
+ return this.apiRequest(name, params, options);
784
+ }
785
+ /**
786
+ * Shortcut method for send PUT request to NGW.
787
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
788
+ * @param options - Request options
789
+ * @param params - Request item params or query params
790
+ */
791
+ put(name, options, params) {
792
+ options = options || {};
793
+ options.method = 'PUT';
794
+ return this.apiRequest(name, params, options);
795
+ }
796
+ /**
797
+ * Shortcut method for send DELETE request to NGW.
798
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
799
+ * @param options - Request options
800
+ * @param params - Request item params or query params
801
+ */
802
+ delete(name, options, params) {
803
+ options = options || {};
804
+ options.method = 'DELETE';
805
+ return this.apiRequest(name, params, options);
806
+ }
807
+ /**
808
+ * Send request to NGW.
809
+ * @param url - URL address to NGW
810
+ * @param params - Query params
811
+ * @param options - Request options
812
+ */
813
+ makeQuery(url, params, options = {}) {
814
+ url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
815
+ if (url) {
816
+ if (params) {
817
+ url = template(url, params);
818
+ }
819
+ url = encodeURI(fixUrlStr(url));
820
+ return this._loadData(url, options);
821
+ }
822
+ else {
823
+ throw new Error('Empty `url` not allowed');
824
+ }
825
+ }
826
+ // -------------------------------------------------------------------------
827
+ // Resource Methods
828
+ // -------------------------------------------------------------------------
829
+ /**
830
+ * {@link ResourcesControl.getOne}
831
+ */
832
+ getResource(resource, requestOptions) {
833
+ return this.resources.getOne(resource, requestOptions);
834
+ }
835
+ /**
836
+ * {@link ResourcesControl.getOneOrFail}
837
+ */
838
+ getResourceOrFail(resource, requestOptions) {
839
+ return this.resources.getOneOrFail(resource, requestOptions);
840
+ }
841
+ /**
842
+ * @deprecated - use {@link getResource}
843
+ */
844
+ getResourceBy(resource) {
845
+ return this.resources.getOne(resource);
846
+ }
847
+ /**
848
+ * @deprecated - use {@link getResource}
849
+ */
850
+ getResourceByKeyname(keyname) {
851
+ return this.resources.getOne(keyname);
852
+ }
853
+ /**
854
+ * @deprecated - use {@link getResource}
855
+ */
856
+ getResourceById(id) {
857
+ return this.resources.getOne(id);
858
+ }
859
+ /**
860
+ * {@link ResourcesControl.getId}
861
+ */
862
+ getResourceId(resource, requestOptions) {
863
+ return this.resources.getId(resource, requestOptions);
864
+ }
865
+ /**
866
+ * {@link ResourcesControl.getIdOrFail}
867
+ */
868
+ getResourceIdOrFail(resource, requestOptions) {
869
+ return this.resources.getIdOrFail(resource, requestOptions);
870
+ }
871
+ /**
872
+ * {@link ResourcesControl.getMany}
873
+ */
874
+ getResourcesBy(resource, requestOptions) {
875
+ return this.resources.getMany(resource, requestOptions);
876
+ }
877
+ /**
878
+ * {@link ResourcesControl.getParent}
879
+ */
880
+ getResourceParent(resource, requestOptions) {
881
+ return this.resources.getParent(resource, requestOptions);
882
+ }
883
+ /**
884
+ * {@link ResourcesControl.getChildrenOf}
885
+ */
886
+ getResourceChildren(resource, requestOptions) {
887
+ return this.resources.getChildrenOf(resource, requestOptions);
888
+ }
889
+ /**
890
+ * {@link ResourcesControl.update}
891
+ */
892
+ updateResource(resource, data) {
893
+ return this.resources.update(resource, data);
894
+ }
895
+ /**
896
+ * {@link ResourcesControl.delete}
897
+ */
898
+ deleteResource(resource) {
899
+ return this.resources.delete(resource);
900
+ }
901
+ /**
902
+ * @internal
903
+ */
904
+ _loadData(url, options) {
905
+ options.responseType = options.responseType || 'json';
906
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
907
+ if (this.user) {
908
+ options = options || {};
909
+ // options.withCredentials = true;
910
+ options.headers = {
911
+ ...this.getAuthorizationHeaders(),
912
+ ...options.headers,
913
+ };
914
+ }
915
+ if (this.requestTransform) {
916
+ const [transUrl, transOptions] = this.requestTransform(url, options);
917
+ url = transUrl;
918
+ options = transOptions;
919
+ }
920
+ loadData(url, resolve, options, reject, onCancel);
921
+ })
922
+ .then((resp) => {
923
+ this._cleanActiveRequests(request);
924
+ return resp;
925
+ })
926
+ .catch((httpError) => {
927
+ this._cleanActiveRequests(request);
928
+ if (httpError instanceof CancelablePromise.CancelError) ;
929
+ else {
930
+ // @ts-ignore
931
+ if ((process.env.NODE_ENV !== 'production')) {
932
+ console.warn('DEV WARN', httpError);
933
+ }
934
+ const er = this._handleHttpError(httpError);
935
+ if (er) {
936
+ throw er;
937
+ }
938
+ }
939
+ });
940
+ if (options.signal &&
941
+ typeof options.signal.addEventListener === 'function') {
942
+ options.signal.addEventListener('abort', () => {
943
+ request.cancel();
944
+ this._cleanActiveRequests(request);
945
+ });
946
+ }
947
+ this.activeRequests.push(request);
948
+ return request;
949
+ }
950
+ _login(credentials, options) {
951
+ return this.getUserInfo(credentials, options)
952
+ .then((data) => {
953
+ this.user = data;
954
+ this.emitter.emit('login', data);
955
+ return data;
956
+ })
957
+ .catch((er) => {
958
+ this.emitter.emit('login:error', er);
959
+ throw er;
960
+ });
961
+ }
962
+ _cleanActiveRequests(request) {
963
+ const activeRequestIndex = this.activeRequests.indexOf(request);
964
+ if (activeRequestIndex !== -1) {
965
+ this.activeRequests.splice(activeRequestIndex, 1);
966
+ }
967
+ }
968
+ _handleHttpError(er) {
969
+ if (er) {
970
+ if (er instanceof NgwError) {
971
+ if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
972
+ throw new ResourceNotFoundError(er);
973
+ }
974
+ else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
975
+ throw new InsufficientPermissionsError(er);
976
+ }
977
+ }
978
+ }
979
+ return er;
980
+ }
981
+ }
982
+ NgwConnector$1.errors = {
983
+ NgwError,
984
+ ResourceNotFoundError,
985
+ };
1124
986
 
1125
- /**
1126
- * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
1127
- *
1128
- * @remarks
1129
- * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
1130
- *
1131
- * @packageDocumentation
1132
- * @module ngw-connector
1133
- */
987
+ /**
988
+ * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
989
+ *
990
+ * @remarks
991
+ * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
992
+ *
993
+ * @packageDocumentation
994
+ * @module ngw-connector
995
+ */
1134
996
  var NgwConnector = NgwConnector$1;
1135
997
 
1136
998
  export { NgwConnector as default };