@nextgis/ngw-connector 1.19.0 → 2.0.0-alpha.1

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