@nextgis/ngw-connector 1.18.21 → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1020 +1,1018 @@
1
- /** Bundle of @nextgis/ngw-connector; version: 1.18.21; author: NextGIS */
1
+ /** Bundle of @nextgis/ngw-connector; version: 2.0.0-alpha.0; author: NextGIS */
2
2
  'use strict';
3
3
 
4
4
  var events = require('events');
5
+ var Cache = require('@nextgis/cache');
5
6
  var CancelablePromise = require('@nextgis/cancelable-promise');
6
7
  var utils = require('@nextgis/utils');
7
- var Cache = require('@nextgis/cache');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
10
-
11
- var CancelablePromise__default = /*#__PURE__*/_interopDefaultLegacy(CancelablePromise);
12
- var Cache__default = /*#__PURE__*/_interopDefaultLegacy(Cache);
13
8
 
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
- function isError(error) {
27
- if (utils.isObject(error)) {
28
- return error.status_code && error.exception && error.title;
29
- }
30
- return false;
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
+ };
37
+ class ResourceNotFoundError extends NgwError {
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
+ }
31
44
  }
32
45
 
33
46
  function isObject(val) {
34
- return Object.prototype.toString.call(val) === '[object Object]';
47
+ return Object.prototype.toString.call(val) === "[object Object]";
35
48
  }
36
49
 
37
- let loadData;
38
- // @ts-ignore
39
- {
40
- const url = require('url');
41
- const http = require('http');
42
- const https = require('https');
43
- const FormData = require('form-data');
44
- const adapterFor = (inputUrl) => {
45
- const adapters = {
46
- 'http:': http,
47
- 'https:': https,
48
- };
49
- const protocol = url.parse(inputUrl).protocol || 'https:';
50
- return adapters[protocol];
51
- };
52
- loadData = (url, callback, options = {}, error, onCancel) => {
53
- const { file, headers, method, data, responseType } = options;
54
- const request = new Promise((resolve, reject) => {
55
- const adapter = adapterFor(url);
56
- if (adapter) {
57
- const requestOpt = {
58
- headers: headers || {},
59
- method,
60
- };
61
- const body = typeof data === 'string' ? data : JSON.stringify(data);
62
- // https://stackoverflow.com/questions/35589109/node-http-delete-request-no-longer-works-after-upgrading-from-0-10-40
63
- let form;
64
- let uploadedFile = file;
65
- if (file) {
66
- const fileMeta = {};
67
- if (isObject(file) &&
68
- 'file' in file &&
69
- ('filename' in file || 'name' in file)) {
70
- const { file: file_, name, ...fileMeta_ } = file;
71
- if (name && !fileMeta_.filename) {
72
- fileMeta_.filename = name;
73
- }
74
- Object.assign(fileMeta, fileMeta_);
75
- uploadedFile = file_;
76
- }
77
- form = new FormData();
78
- form.append('file', uploadedFile, fileMeta);
79
- if (data) {
80
- for (const d in data) {
81
- form.append(d, data[d]);
82
- }
83
- }
84
- Object.assign(requestOpt.headers, {
85
- // 'content-length': form.getLengthSync(),
86
- ...form.getHeaders(),
87
- });
88
- }
89
- if (body !== undefined) {
90
- Object.assign(requestOpt.headers, {
91
- 'content-type': 'application/json',
92
- 'content-length': Buffer.byteLength(body),
93
- });
94
- }
95
- const req = adapter.request(url, requestOpt, (resp) => {
96
- let data = '';
97
- resp.on('data', (chunk) => {
98
- data += chunk;
99
- });
100
- resp.on('end', () => {
101
- if (data) {
102
- if (responseType === 'blob') {
103
- resolve(data);
104
- }
105
- else {
106
- let json;
107
- try {
108
- json = JSON.parse(data);
109
- if (json && json.status_code && json.status_code) {
110
- reject(json.message);
111
- }
112
- }
113
- catch (er) {
114
- reject(er);
115
- }
116
- if (json !== undefined) {
117
- if (isError(json)) {
118
- reject('extractError(json)');
119
- }
120
- else {
121
- resolve(json);
122
- }
123
- }
124
- }
125
- }
126
- reject('no data');
127
- });
128
- });
129
- if (form) {
130
- form.pipe(req);
131
- }
132
- req.on('error', (err) => {
133
- reject(err);
134
- });
135
- if (body) {
136
- req.write(body);
137
- }
138
- onCancel(() => {
139
- req.abort();
140
- });
141
- req.end();
142
- }
143
- else {
144
- throw new Error(`Given URL '${url}' is not correct`);
145
- }
146
- });
147
- return request
148
- .then((data) => {
149
- if (callback) {
150
- callback(data);
151
- }
152
- return data;
153
- })
154
- .catch((er) => {
155
- if (error) {
156
- error(er);
157
- }
158
- else {
159
- throw new Error(er);
160
- }
161
- });
162
- };
50
+ function resourceCompare(res1, res2) {
51
+ return utils.objectDeepEqual(res1, res2);
163
52
  }
164
53
 
165
- // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
166
- const templateRe = /\{ *([\w_-]+) *\}/g;
167
- function template(str, data) {
168
- return str.replace(templateRe, (s, key) => {
169
- let value = data[key];
170
- if (value === undefined) {
171
- throw new Error('No value provided for letiable ' + s);
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;
172
66
  }
173
- else if (typeof value === 'function') {
174
- value = value(data);
175
- }
176
- return value;
177
- });
67
+ } else if (utils.defined(value)) {
68
+ query[prefix + key] = value;
69
+ }
70
+ }
71
+ }
72
+ return query;
178
73
  }
179
74
 
180
- function apiRequest(opt) {
181
- const params = opt.params;
182
- return new CancelablePromise__default((resolve, reject) => {
183
- opt.connector
184
- .connect()
185
- .then((apiItems) => {
186
- let apiItem = apiItems && apiItems[opt.name];
187
- if (apiItem) {
188
- apiItem = [...apiItem];
189
- let url = apiItem.shift();
190
- if (apiItem.length) {
191
- const replaceParams = {};
192
- for (let fry = 0; fry < apiItem.length; fry++) {
193
- const arg = apiItem[fry];
194
- replaceParams[fry] = '{' + arg + '}';
195
- if (params[arg] === undefined) {
196
- throw new Error('`' + arg + '`' + ' url api argument is not specified');
197
- }
198
- }
199
- if (url) {
200
- url = template(url, replaceParams);
201
- }
202
- }
203
- // Transfer part of the parameters from `params` to the URL string
204
- if (params) {
205
- const paramArray = [];
206
- const paramList = params.paramList;
207
- if (Array.isArray(paramList)) {
208
- delete params.paramList;
209
- paramList.forEach((x) => {
210
- paramArray.push(`${x[0]}=${x[1]}`);
211
- });
212
- }
213
- for (const p in params) {
214
- if (apiItem.indexOf(p) === -1) {
215
- paramArray.push(`${p}=${params[p]}`);
216
- }
217
- }
218
- if (paramArray.length) {
219
- url = url + '?' + paramArray.join('&');
220
- }
221
- }
222
- if (url) {
223
- resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
224
- }
225
- else {
226
- reject(new Error('request url is not set'));
227
- }
228
- }
229
- else {
230
- resolve(undefined);
231
- }
232
- })
233
- .catch((er) => {
234
- reject(er);
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
+ };
81
+ class ResourcesControl {
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;
110
+ }
111
+ if (resource.display_name) {
112
+ forCache.display_name = resource.display_name;
113
+ }
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;
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));
182
+ }
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;
235
195
  });
196
+ }
197
+ return items;
236
198
  });
237
- }
238
-
239
- /**
240
- * Thrown when ...
241
- */
242
- class ResourceNotFoundError extends NgwError {
243
- constructor(obj) {
244
- super(obj);
245
- this.name = 'ResourceNotFoundError';
246
- this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
247
- Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
248
- }
249
- }
250
-
251
- /**
252
- * Thrown when ...
253
- */
254
- class InsufficientPermissionsError extends NgwError {
255
- constructor(obj) {
256
- super(obj);
257
- this.name = 'InsufficientPermissionsError';
258
- this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
259
- Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
260
- }
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;
230
+ });
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
246
+ });
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
+ );
252
+ }
253
+ }
254
+ if (recursivePromises.length) {
255
+ return CancelablePromise.all(recursivePromises).then(() => {
256
+ return _items;
257
+ });
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
+ }
314
+ });
315
+ return items;
316
+ }
317
+ );
318
+ }
261
319
  }
262
320
 
263
321
  const CONNECTORS = [];
264
322
  function addConnector(connector) {
265
- CONNECTORS.push(connector);
323
+ CONNECTORS.push(connector);
266
324
  }
267
325
  function findConnector(options) {
268
- return CONNECTORS.find((x) => {
269
- if (x.options.baseUrl === options.baseUrl) {
270
- if (options.auth) {
271
- if (x.options.auth) {
272
- return utils.objectDeepEqual(x.options.auth, options.auth);
273
- }
274
- }
275
- else {
276
- // if auth not in find options; use first connector with same url
277
- return true;
278
- }
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);
279
331
  }
280
- });
332
+ } else {
333
+ return true;
334
+ }
335
+ }
336
+ });
281
337
  }
282
338
  function removeConnector(connector) {
283
- const index = CONNECTORS.indexOf(connector);
284
- if (index !== -1) {
285
- CONNECTORS.splice(index, 1);
286
- }
339
+ const index = CONNECTORS.indexOf(connector);
340
+ if (index !== -1) {
341
+ CONNECTORS.splice(index, 1);
342
+ }
287
343
  }
288
344
 
289
- const exclude = ['description'];
290
- /**
291
- * @remarks
292
- * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
293
- *
294
- * ```
295
- * { keyname, owner_user: { id }} > { keyname, owner_user__id }
296
- * ```
297
- *
298
- * @param resource - Any property from NGW resource item
299
- */
300
- function resourceToQuery(resource, prefix = '') {
301
- prefix = prefix ? prefix + '__' : '';
302
- const query = {};
303
- for (const [key, value] of Object.entries(resource)) {
304
- if (exclude.indexOf(key) === -1) {
305
- if (isObject(value)) {
306
- if (key === 'owner_user') {
307
- const children = resourceToQuery(value, key);
308
- Object.assign(query, children);
309
- }
310
- else if (key === 'parent' && 'id' in value) {
311
- query.parent_id = value.id;
312
- }
313
- }
314
- else if (utils.defined(value)) {
315
- query[prefix + key] = value;
316
- }
317
- }
318
- }
319
- return query;
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
+ };
351
+ class InsufficientPermissionsError extends NgwError {
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
+ }
320
358
  }
321
359
 
322
- function resourceCompare(res1, res2) {
323
- return utils.objectDeepEqual(res1, res2);
360
+ const templateRe = /\{ *([\w_-]+) *\}/g;
361
+ function template(str, data) {
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
+ });
324
371
  }
325
372
 
326
- class ResourcesControl {
327
- constructor(connector) {
328
- this.connector = connector;
329
- this.cache = new Cache__default();
330
- }
331
- // -------------------------------------------------------------------------
332
- // Resource Methods
333
- // -------------------------------------------------------------------------
334
- /**
335
- * Receive resource from NGW by id, keyname or search-object parameter.
336
- * @param resource - Resource id, keyname or search-object
337
- *
338
- * @remarks
339
- * Fetching resource would be cached to speed up next call
340
- */
341
- getOne(resource, requestOptions) {
342
- const cache = new Cache__default();
343
- const forCache = {};
344
- const opt = { ...requestOptions, cache: false };
345
- if (typeof resource === 'string') {
346
- forCache.keyname = resource;
373
+ function apiRequest(opt) {
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
+ }
347
395
  }
348
- else if (typeof resource === 'number') {
349
- forCache.id = resource;
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
+ }
350
413
  }
351
- else if (isObject(resource)) {
352
- if (resource.id !== undefined) {
353
- forCache.id = resource.id;
354
- }
355
- else if (resource.keyname) {
356
- forCache.keyname = resource.keyname;
357
- }
414
+ if (url) {
415
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
416
+ } else {
417
+ reject(new Error("request url is not set"));
358
418
  }
359
- const makeRequest = () => {
360
- if (typeof resource === 'string') {
361
- return this._fetchResourceBy({ keyname: resource }, opt);
362
- }
363
- else if (typeof resource === 'number') {
364
- return this._fetchResourceById(resource, opt);
365
- }
366
- else if (isObject(resource)) {
367
- return this._fetchResourceBy(resource, opt);
368
- }
369
- return CancelablePromise__default.resolve(undefined);
419
+ } else {
420
+ resolve(void 0);
421
+ }
422
+ }).catch((er) => {
423
+ reject(er);
424
+ });
425
+ });
426
+ }
427
+
428
+ function isError(error) {
429
+ if (utils.isObject(error)) {
430
+ return error.status_code && error.exception && error.title;
431
+ }
432
+ return false;
433
+ }
434
+
435
+ let loadData;
436
+ {
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
445
+ };
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
370
457
  };
371
- return cache.addFull('resource', makeRequest, forCache);
372
- }
373
- getOneOrFail(resource, requestOptions) {
374
- return this.getOne(resource, requestOptions).then((res) => {
375
- if (res) {
376
- return res;
377
- }
378
- throw new ResourceNotFoundError();
379
- });
380
- }
381
- /**
382
- * A fast way to retrieve resource ID for any resource definition.
383
- * @param resource - Any available resource definition
384
- *
385
- * @remarks
386
- * There are situations when exactly the resource id is needed
387
- * (for example, to compose the correct request to the api)
388
- * then this method will come in handy to facilitate the extraction of the identifier
389
- * if the resource is specified through a keyname or other parameters.
390
- */
391
- getId(resource, requestOptions) {
392
- if (typeof resource === 'number') {
393
- return CancelablePromise__default.resolve(resource);
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
+ });
394
486
  }
395
- else if (typeof resource === 'string' || isObject(resource)) {
396
- return this.getOne(resource, requestOptions).then((res) => {
397
- if (res) {
398
- return res.resource.id;
399
- }
400
- });
487
+ if (body !== void 0) {
488
+ Object.assign(requestOpt.headers, {
489
+ "content-type": "application/json",
490
+ "content-length": Buffer.byteLength(body)
491
+ });
401
492
  }
402
- return CancelablePromise__default.resolve(undefined);
403
- }
404
- /**
405
- * A fast way to retrieve resource ID for any resource definition.
406
- * @param resource - Any available resource definition
407
- *
408
- * @remarks
409
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
410
- * To not make one more checks if the resource is definitely exists
411
- */
412
- getIdOrFail(resource, requestOptions) {
413
- return this.getId(resource, requestOptions).then((resp) => {
414
- if (resp === undefined) {
415
- throw new Error();
416
- }
417
- return resp;
418
- });
419
- }
420
- getMany(resource, requestOptions) {
421
- return this._resourceCacheFilter(resource).then((items) => {
422
- if (!items.length) {
423
- const query = {};
424
- if (resource.keyname) {
425
- query.keyname = resource.keyname;
426
- }
427
- else {
428
- Object.assign(query, resourceToQuery(resource));
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);
429
511
  }
430
- return this.connector
431
- .get('resource.search', requestOptions, {
432
- serialization: 'full',
433
- ...query,
434
- })
435
- .then((resources) => {
436
- if (resources) {
437
- for (const x of resources) {
438
- this.cache.add('resource.item', CancelablePromise__default.resolve(x), {
439
- id: x.resource.id,
440
- });
441
- }
442
- }
443
- return resources;
444
- });
445
- }
446
- return items;
447
- });
448
- }
449
- getParent(resource, requestOptions) {
450
- return this.getOne(resource, requestOptions).then((child) => {
451
- if (child) {
452
- return this.getOne(child.resource.parent.id, requestOptions);
453
- }
454
- return CancelablePromise__default.resolve(undefined);
455
- });
456
- }
457
- getChildrenOf(resource, requestOptions) {
458
- return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
459
- }
460
- update(resource, data) {
461
- return this.getId(resource).then((id) => {
462
- if (id !== undefined) {
463
- return this.connector.put('resource.item', { data }, { id });
464
- }
465
- });
466
- }
467
- /**
468
- * Fast way to delete resource from NGW and clean cache.
469
- * @param resource - Resource definition
470
- */
471
- delete(resource) {
472
- return this.getId(resource).then((id) => {
473
- if (id !== undefined) {
474
- return this.connector.delete('resource.item', null, { id }).then(() => {
475
- this._cleanResourceItemCache(id);
476
- return undefined;
477
- });
478
- }
479
- });
480
- }
481
- _getChildrenOf(parent, requestOptions, _items = []) {
482
- return this.connector
483
- .get('resource.collection', { cache: true, ...requestOptions }, {
484
- parent,
485
- })
486
- .then((items) => {
487
- const recursivePromises = [];
488
- for (const item of items) {
489
- this.cache.add('resource.item', CancelablePromise__default.resolve(item), {
490
- id: item.resource.id,
491
- });
492
- _items.push(item);
493
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
494
- recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
512
+ if (json !== void 0) {
513
+ if (isError(json)) {
514
+ reject("extractError(json)");
515
+ } else {
516
+ resolve(json);
517
+ }
495
518
  }
519
+ }
496
520
  }
497
- if (recursivePromises.length) {
498
- return CancelablePromise__default.all(recursivePromises).then(() => {
499
- return _items;
500
- });
501
- }
502
- return _items;
521
+ reject("no data");
522
+ });
503
523
  });
504
- }
505
- async _cleanResourceItemCache(id) {
506
- const all = this.cache.all();
507
- const toDelete = [];
508
- for (const c of all) {
509
- const cid = c.options && c.options.id;
510
- if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
511
- if (typeof cid === 'number') {
512
- if (cid === id) {
513
- toDelete.push(c);
514
- }
515
- }
516
- else {
517
- const rid = await this.getId(cid);
518
- if (rid === id) {
519
- toDelete.push(c);
520
- }
521
- }
522
- }
524
+ if (form) {
525
+ form.pipe(req);
523
526
  }
524
- for (const d of toDelete) {
525
- this.cache.delete(d);
526
- }
527
- }
528
- _fetchResourceById(id, requestOptions) {
529
- const promise = () => this.connector.get('resource.item', requestOptions, { id });
530
- return this.cache
531
- .add('resource.item', promise, {
532
- id,
533
- })
534
- .catch((er) => {
535
- if (!(er instanceof ResourceNotFoundError)) {
536
- throw er;
537
- }
538
- return undefined;
527
+ req.on("error", (err) => {
528
+ reject(err);
539
529
  });
540
- }
541
- _fetchResourceBy(resource, requestOptions) {
542
- return this.getMany(resource, requestOptions).then((resources) => {
543
- return resources[0];
544
- });
545
- }
546
- _resourceCacheFilter(resource) {
547
- return CancelablePromise__default.all(this.cache.matchAll('resource.item')).then((resources) => {
548
- const items = [];
549
- resources.filter((x) => {
550
- if (x) {
551
- // identical by uniq props
552
- if (resource.keyname && x.resource.keyname) {
553
- return resource.keyname === x.resource.keyname;
554
- }
555
- if (utils.defined(resource.id) && utils.defined(x.resource.id)) {
556
- return resource.id === x.resource.id;
557
- }
558
- return resourceCompare(resource, x.resource);
559
- }
560
- });
561
- return items;
530
+ if (body) {
531
+ req.write(body);
532
+ }
533
+ onCancel(() => {
534
+ req.abort();
562
535
  });
563
- }
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;
999
971
  }
1000
- return er;
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);
1006
+ }
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