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