@nextgis/ngw-connector 1.9.3 → 1.11.3
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.
- package/README.md +125 -120
- package/lib/index.d.ts +75 -4
- package/lib/ngw-connector.cjs.js +61 -27
- package/lib/ngw-connector.cjs.js.map +1 -1
- package/lib/ngw-connector.cjs.prod.js +1 -1
- package/lib/ngw-connector.cjs.prod.js.map +1 -1
- package/lib/ngw-connector.esm-browser.js +92 -33
- package/lib/ngw-connector.esm-browser.js.map +1 -1
- package/lib/ngw-connector.esm-browser.prod.js +1 -1
- package/lib/ngw-connector.esm-browser.prod.js.map +1 -1
- package/lib/ngw-connector.esm-bundler.js +9 -9
- package/lib/ngw-connector.esm-bundler.js.map +1 -1
- package/lib/ngw-connector.esm-bundler.prod.js +1 -1
- package/lib/ngw-connector.esm-bundler.prod.js.map +1 -1
- package/lib/ngw-connector.global.js +105 -41
- package/lib/ngw-connector.global.js.map +1 -1
- package/lib/ngw-connector.global.prod.js +1 -1
- package/lib/ngw-connector.global.prod.js.map +1 -1
- package/package.json +8 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ngw-connector.esm-bundler.prod.js","sources":["../src/errors/NgwError.ts","../src/errors/NetworkError.ts","../src/utils/loadData.ts","../src/utils/template.ts","../src/errors/ResourceNotFoundError.ts","../src/errors/InsufficientPermissionsError.ts","../src/activeConnectors.ts","../src/utils/isObject.ts","../src/utils/resourceToQuery.ts","../src/ResourcesControl.ts","../src/utils/resourceCompare.ts","../src/NgwConnector.ts","../src/utils/apiRequest.ts","../src/index.ts"],"sourcesContent":["import { NgwExceptions } from '../interfaces';\n\n/**\n * Thrown when...\n */\nexport class NgwError extends Error {\n name = 'NgwError';\n\n title!: string;\n message!: string;\n detail!: string;\n exception!: NgwExceptions;\n status_code!: number | 404 | 500;\n data?: Record<string, any>;\n guru_meditation!: string;\n\n constructor(er?: NgwError) {\n super();\n Object.assign(this, er);\n Object.setPrototypeOf(this, NgwError.prototype);\n }\n}\n","/**\n * Thrown when...\n */\nexport class NetworkError extends Error {\n name = 'NetworkError';\n\n constructor(url: string) {\n super();\n Object.setPrototypeOf(this, NetworkError.prototype);\n this.message = `Unable to request ${url}.\n Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors\n }\n}\n","import {\n RequestOptions as NgwRequestOptions,\n RequestMethods,\n} from '../interfaces';\nimport { NgwError } from '../errors/NgwError';\nimport { NetworkError } from '../errors/NetworkError';\n\n// readyState\n// Holds the status of the XMLHttpRequest.\n// 0: request not initialized\n// 1: server connection established\n// 2: request received\n// 3: processing request\n// 4: request finished and response is ready\n\n// status\n// 200: \"OK\"\n// 201 \"Created\"\tThe request has been fulfilled, and a new resource is created\n// 403: \"Forbidden\"\n// 404: \"Page not found\"\n// 500: \"Internal Server Error\"\n// For a complete list go to the Http Messages Reference\n\ntype LoadData = (\n url: string,\n callback: (...args: any[]) => any,\n options: NgwRequestOptions<RequestMethods> | undefined,\n error: (reason?: any) => void,\n onCancel: (cancelHandler: () => void) => void,\n) => void;\n\nlet loadData: LoadData;\n// @ts-ignore\nif (__BROWSER__) {\n loadData = (\n url: string,\n callback: (...args: any[]) => any,\n options: NgwRequestOptions = {},\n error: (reason?: any) => void,\n onCancel: (cancelHandler: () => void) => void,\n ): void => {\n options.method = options.method || 'GET';\n\n const xhr = new XMLHttpRequest();\n xhr.open(options.method || 'GET', url, true); // true for asynchronous\n\n if (options.responseType === 'blob') {\n xhr.responseType = options.responseType;\n }\n const getResponseText = () => {\n try {\n return JSON.parse(xhr.responseText);\n } catch (er) {\n return xhr.responseText;\n }\n };\n const processingResponse = (forError = false) => {\n const cb = forError ? error : callback;\n if (options.responseType === 'blob') {\n cb(xhr.response);\n } else {\n if (xhr.responseText) {\n cb(getResponseText());\n } else {\n error({ message: '' });\n }\n }\n };\n xhr.onload = () => {\n if ([401, 403, 404, 500].indexOf(xhr.status) !== -1) {\n error(new NgwError(getResponseText()));\n }\n processingResponse();\n };\n\n // xhr.onreadystatechange = () => {\n // if (\n // (xhr.readyState === 4 && xhr.status === 200) ||\n // (xhr.readyState === 3 && xhr.status === 201)\n // ) {\n // processingResponse();\n // } else if (xhr.readyState === 3 && xhr.status === 400) {\n // processingResponse();\n // } else if (xhr.readyState === 4 && xhr.status === 500) {\n // processingResponse();\n // } else if (xhr.readyState === 4 && xhr.status === 401) {\n // error(xhr.statusText);\n // } else if (xhr.readyState === 4) {\n // error('request error');\n // }\n // };\n\n xhr.onerror = (er) => {\n if (xhr.status === 0) {\n error(new NetworkError(url));\n } else {\n error(er);\n }\n };\n\n xhr.upload.onprogress = function (e) {\n if (e.lengthComputable) {\n const percentComplete = (e.loaded / e.total) * 100;\n if (options.onProgress) {\n options.onProgress(percentComplete, e);\n }\n // console.log(percentComplete + '% uploaded');\n }\n };\n\n const headers = options.headers;\n if (headers) {\n for (const h in headers) {\n const header = headers[h];\n if (typeof header === 'string') {\n xhr.setRequestHeader(h, header);\n }\n }\n }\n if (options.withCredentials !== undefined) {\n xhr.withCredentials = options.withCredentials;\n }\n\n let data: FormData | any;\n if (options.file) {\n data = new FormData();\n data.append('file', options.file);\n if (options.data) {\n for (const d in data) {\n data.append(d, data[d]);\n }\n }\n } else {\n data = options.data\n ? typeof options.data === 'string'\n ? options.data\n : JSON.stringify(options.data)\n : null;\n }\n if (onCancel) {\n onCancel(() => {\n xhr.abort();\n });\n }\n xhr.send(data);\n };\n} else {\n const url = require('url');\n const http = require('http');\n const https = require('https');\n\n const adapterFor = (inputUrl: string) => {\n const adapters: Record<string, any> = {\n 'http:': http,\n 'https:': https,\n };\n const protocol = url.parse(inputUrl).protocol || 'https:';\n return adapters[protocol];\n };\n\n loadData = (\n url: string,\n callback: (...args: any[]) => any,\n options: NgwRequestOptions<RequestMethods> = {},\n error: (reason?: any) => void,\n onCancel: (cancelHandler: () => void) => void,\n ): Promise<unknown> => {\n const request = new Promise((resolve, reject) => {\n const adapter = adapterFor(url);\n if (adapter) {\n const requestOpt = {\n headers: options.headers || {},\n method: options.method,\n };\n const body =\n typeof options.data === 'string'\n ? options.data\n : JSON.stringify(options.data);\n // https://stackoverflow.com/questions/35589109/node-http-delete-request-no-longer-works-after-upgrading-from-0-10-40\n if (body !== undefined && options.method !== 'POST') {\n Object.assign(requestOpt.headers, {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(body),\n });\n }\n const req = adapter.request(url, requestOpt, (resp: any) => {\n let data = '';\n resp.on('data', (chunk: any) => {\n data += chunk;\n });\n resp.on('end', () => {\n if (data) {\n let json: Record<string, any> | undefined;\n try {\n json = JSON.parse(data);\n if (json && json.status_code && json.status_code) {\n reject(json.message);\n }\n } catch (er) {\n reject(er);\n // throw new Error(er);\n }\n if (json !== undefined) {\n resolve(json);\n }\n }\n reject('no data');\n });\n });\n req.on('error', (err: any) => {\n reject(err);\n });\n if (body) {\n req.write(body);\n }\n onCancel(() => {\n req.abort();\n });\n req.end();\n } else {\n throw new Error(`Given URL '${url}' is not correct`);\n }\n });\n return request\n .then((data) => {\n if (callback) {\n callback(data);\n }\n return data;\n })\n .catch((er) => {\n if (error) {\n error(er);\n } else {\n throw new Error(er);\n }\n });\n };\n}\n\nexport { loadData };\n","// https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165\nconst templateRe = /\\{ *([\\w_-]+) *\\}/g;\n\nexport function template(str: string, data: { [param: string]: any }): string {\n return str.replace(templateRe, (s, key) => {\n let value = data[key];\n\n if (value === undefined) {\n throw new Error('No value provided for letiable ' + s);\n } else if (typeof value === 'function') {\n value = value(data);\n }\n return value;\n });\n}\n","import { NgwError } from './NgwError';\nimport { NgwExceptions } from '../interfaces';\n\n/**\n * Thrown when ...\n */\nexport class ResourceNotFoundError extends NgwError {\n name = 'ResourceNotFoundError';\n exception: NgwExceptions = 'nextgisweb.resource.exception.ResourceNotFound';\n\n constructor(obj?: ResourceNotFoundError) {\n super(obj);\n Object.setPrototypeOf(this, ResourceNotFoundError.prototype);\n }\n}\n","import { NgwError } from './NgwError';\nimport { NgwExceptions } from '../interfaces';\n\n/**\n * Thrown when ...\n */\nexport class InsufficientPermissionsError extends NgwError {\n name = 'InsufficientPermissionsError';\n exception: NgwExceptions =\n 'nextgisweb.core.exception.InsufficientPermissions';\n\n constructor(obj: InsufficientPermissionsError) {\n super(obj);\n Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);\n }\n}\n","import { NgwConnectorOptions } from './interfaces';\nimport { NgwConnector } from './NgwConnector';\nimport { objectDeepEqual } from '@nextgis/utils';\n\nexport const CONNECTORS: NgwConnector[] = [];\n\nexport function addConnector(connector: NgwConnector): void {\n CONNECTORS.push(connector);\n}\n\nexport function findConnector(\n options: NgwConnectorOptions,\n): NgwConnector | undefined {\n return CONNECTORS.find((x) => {\n if (x.options.baseUrl === options.baseUrl) {\n if (options.auth) {\n if (x.options.auth) {\n return objectDeepEqual(x.options.auth, options.auth);\n }\n } else {\n // if auth not in find options; use first connector with same url\n return true;\n }\n }\n });\n}\n\nexport function removeConnector(connector: NgwConnector): void {\n const index = CONNECTORS.indexOf(connector);\n if (index !== -1) {\n CONNECTORS.splice(index, 1);\n }\n}\n\nexport function findAndRemoveConnector(options: NgwConnectorOptions): void {\n const exist = findConnector(options);\n if (exist) {\n removeConnector(exist);\n }\n}\n","export function isObject(val: unknown): val is Record<string | number, any> {\n return Object.prototype.toString.call(val) === '[object Object]';\n}\n","import { DeepPartial, defined } from '@nextgis/utils';\nimport { Resource } from '../types/ResourceItem';\nimport { isObject } from './isObject';\n\nconst exclude = ['description'];\n\n/**\n * @remarks\n * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources\n *\n * ```\n * { keyname, owner_user: { id }} > { keyname, owner_user__id }\n * ```\n *\n * @param resource - Any property from NGW resource item\n */\nexport function resourceToQuery(\n resource: DeepPartial<Resource>,\n prefix = '',\n): Record<string, unknown> {\n prefix = prefix ? prefix + '__' : '';\n const query: Record<string, any> = {};\n for (const [key, value] of Object.entries(resource)) {\n if (exclude.indexOf(key) === -1) {\n if (isObject(value)) {\n if (key === 'owner_user') {\n const children = resourceToQuery(value as DeepPartial<Resource>, key);\n Object.assign(query, children);\n } else if (key === 'parent' && 'id' in value) {\n query.parent_id = value.id;\n }\n } else if (defined(value)) {\n query[prefix + key] = value;\n }\n }\n }\n return query;\n}\n","import CancelablePromise from '@nextgis/cancelable-promise';\nimport { defined } from '@nextgis/utils';\nimport Cache from '@nextgis/cache';\n\nimport { resourceToQuery } from './utils/resourceToQuery';\nimport { resourceCompare } from './utils/resourceCompare';\nimport { ResourceNotFoundError } from './errors/ResourceNotFoundError';\n\nimport { isObject } from './utils/isObject';\n\nimport type { DeepPartial } from '@nextgis/utils';\nimport type { NgwConnector } from './NgwConnector';\nimport type { ResourceItem, Resource } from './types/ResourceItem';\nimport type { RequestOptions, ResourceDefinition } from './interfaces';\n\nexport class ResourcesControl {\n cache = new Cache<\n CancelablePromise<ResourceItem | undefined>,\n { id?: number | string }\n >();\n\n constructor(private connector: NgwConnector) {}\n\n // -------------------------------------------------------------------------\n // Resource Methods\n // -------------------------------------------------------------------------\n\n /**\n * Receive resource from NGW by id, keyname or search-object parameter.\n * @param resource - Resource id, keyname or search-object\n *\n * @remarks\n * Fetching resource would be cached to speed up next call\n */\n getOne(\n resource: ResourceDefinition,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem | undefined> {\n const cache = new Cache();\n const forCache: { keyname?: string; id?: number } = {};\n const opt = { ...requestOptions, cache: false };\n if (typeof resource === 'string') {\n forCache.keyname = resource;\n } else if (typeof resource === 'number') {\n forCache.id = resource;\n } else if (isObject(resource)) {\n forCache.id = resource.id;\n }\n const makeRequest = () => {\n if (typeof resource === 'string') {\n return this._fetchResourceBy({ keyname: resource }, opt);\n } else if (typeof resource === 'number') {\n return this._fetchResourceById(resource, opt);\n } else if (isObject(resource)) {\n return this._fetchResourceBy(resource, opt);\n }\n return CancelablePromise.resolve(undefined);\n };\n\n return cache.addFull('resource', makeRequest, forCache);\n }\n\n getOneOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem> {\n return this.getOne(resource, requestOptions).then((res) => {\n if (res) {\n return res;\n }\n throw new ResourceNotFoundError();\n });\n }\n\n /**\n * A fast way to retrieve resource ID for any resource definition.\n * @param resource - Any available resource definition\n *\n * @remarks\n * There are situations when exactly the resource id is needed\n * (for example, to compose the correct request to the api)\n * then this method will come in handy to facilitate the extraction of the identifier\n * if the resource is specified through a keyname or other parameters.\n */\n getId(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number | undefined> {\n if (typeof resource === 'number') {\n return CancelablePromise.resolve(resource);\n } else if (typeof resource === 'string' || isObject(resource)) {\n return this.getOne(resource, requestOptions).then((res) => {\n if (res) {\n return res.resource.id;\n }\n });\n }\n return CancelablePromise.resolve(undefined);\n }\n\n /**\n * A fast way to retrieve resource ID for any resource definition.\n * @param resource - Any available resource definition\n *\n * @remarks\n * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.\n * To not make one more checks if the resource is definitely exists\n */\n getIdOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number> {\n return this.getId(resource, requestOptions).then((resp) => {\n if (resp === undefined) {\n throw new Error();\n }\n return resp;\n });\n }\n\n getMany(\n resource: DeepPartial<Resource>,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem[]> {\n return this._resourceCacheFilter(resource).then((items) => {\n if (!items.length) {\n const query: Record<string, unknown> = {};\n if (resource.keyname) {\n query.keyname = resource.keyname;\n } else {\n Object.assign(query, resourceToQuery(resource));\n }\n return this.connector\n .get('resource.search', requestOptions, {\n serialization: 'full',\n ...query,\n })\n .then((resources) => {\n if (resources) {\n for (const x of resources) {\n this.cache.add('resource.item', CancelablePromise.resolve(x), {\n id: x.resource.id,\n });\n }\n }\n return resources;\n });\n }\n return items;\n });\n }\n\n getParent(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.getOne(resource, requestOptions).then((child) => {\n if (child) {\n return this.getOne(child.resource.parent.id, requestOptions);\n }\n return CancelablePromise.resolve(undefined);\n });\n }\n\n getChildrenOf(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem[]> {\n return this.getId(resource).then((parent) => {\n return this.connector\n .get(\n 'resource.collection',\n { cache: true, ...requestOptions },\n {\n parent,\n },\n )\n .then((items) => {\n for (const i of items) {\n this.cache.add('resource.item', CancelablePromise.resolve(i), {\n id: i.resource.id,\n });\n }\n return items;\n });\n });\n }\n\n update(\n resource: ResourceDefinition,\n data: DeepPartial<ResourceItem>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.getId(resource).then((id) => {\n if (id !== undefined) {\n return this.connector.put('resource.item', { data }, { id });\n }\n });\n }\n\n /**\n * Fast way to delete resource from NGW and clean cache.\n * @param resource - Resource definition\n */\n delete(resource: ResourceDefinition): CancelablePromise<void> {\n return this.getId(resource).then((id) => {\n if (id !== undefined) {\n return this.connector.delete('resource.item', null, { id }).then(() => {\n this._cleanResourceItemCache(id);\n return undefined;\n });\n }\n });\n }\n\n private async _cleanResourceItemCache(id: number) {\n const all = this.cache.all();\n const toDelete: typeof all = [];\n for (const c of all) {\n const cid = c.options && c.options.id;\n if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {\n if (typeof cid === 'number') {\n if (cid === id) {\n toDelete.push(c);\n }\n } else {\n const rid = await this.getId(cid);\n if (rid === id) {\n toDelete.push(c);\n }\n }\n }\n }\n for (const d of toDelete) {\n this.cache.delete(d);\n }\n }\n\n private _fetchResourceById(\n id: number,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem | undefined> {\n const promise = () =>\n this.connector.get('resource.item', requestOptions, { id }).catch();\n\n return this.cache\n .add('resource.item', promise, {\n id,\n })\n .catch((er) => {\n if (!(er instanceof ResourceNotFoundError)) {\n throw er;\n }\n return undefined;\n });\n }\n\n private _fetchResourceBy(\n resource: DeepPartial<Resource>,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.getMany(resource, requestOptions).then((resources) => {\n return resources[0];\n });\n }\n\n private _resourceCacheFilter(\n resource: DeepPartial<Resource>,\n ): CancelablePromise<ResourceItem[]> {\n return CancelablePromise.all(this.cache.matchAll('resource.item')).then(\n (resources) => {\n const items: ResourceItem[] = [];\n resources.filter((x) => {\n if (x) {\n // identical by uniq props\n if (resource.keyname && x.resource.keyname) {\n return resource.keyname === x.resource.keyname;\n }\n if (defined(resource.id) && defined(x.resource.id)) {\n return resource.id === x.resource.id;\n }\n return resourceCompare(resource, x.resource);\n }\n });\n return items;\n },\n );\n }\n}\n","import { objectDeepEqual } from '@nextgis/utils';\nimport type { DeepPartial } from '@nextgis/utils';\nimport type { Resource } from '../types/ResourceItem';\n\nexport function resourceCompare(\n res1: DeepPartial<Resource>,\n res2: DeepPartial<Resource>,\n): boolean {\n return objectDeepEqual(res1, res2);\n}\n","import { EventEmitter } from 'events';\nimport CancelablePromise from '@nextgis/cancelable-promise';\nimport { objectRemoveEmpty } from '@nextgis/utils';\nimport { fixUrlStr } from '@nextgis/utils';\nimport Cache from '@nextgis/cache';\n\nimport { loadData } from './utils/loadData';\nimport { template } from './utils/template';\nimport { NgwError } from './errors/NgwError';\nimport { ResourceNotFoundError } from './errors/ResourceNotFoundError';\nimport { InsufficientPermissionsError } from './errors/InsufficientPermissionsError';\nimport {\n addConnector,\n findConnector,\n removeConnector,\n} from './activeConnectors';\nimport { ResourcesControl } from './ResourcesControl';\n\nimport type { DeepPartial } from '@nextgis/utils';\nimport type {\n DeleteRequestItemsResponseMap,\n PatchRequestItemsResponseMap,\n PostRequestItemsResponseMap,\n GetRequestItemsResponseMap,\n PutRequestItemsResponseMap,\n ResourceIdKeynameDef,\n NgwConnectorOptions,\n ResourceDefinition,\n RequestItemsParams,\n RequestItemKeys,\n RequestHeaders,\n RequestOptions,\n PyramidRoute,\n Credentials,\n UserInfo,\n Params,\n} from './interfaces';\nimport type { RequestItemsParamsMap } from './types/RequestItemsParamsMap';\nimport type { ResourceItem, Resource } from './types/ResourceItem';\nimport { apiRequest } from './utils/apiRequest';\n\nlet ID = 0;\n\nexport class NgwConnector {\n static errors = {\n NgwError,\n ResourceNotFoundError,\n };\n id = ID++;\n\n emitter = new EventEmitter();\n user?: UserInfo;\n\n resources!: ResourcesControl;\n\n private routeStr = '/api/component/pyramid/route';\n\n constructor(public options: NgwConnectorOptions) {\n const exist = findConnector(options);\n if (exist) {\n return exist;\n } else {\n if (this.options.route) {\n this.routeStr = this.options.route;\n }\n this.resources = new ResourcesControl(this);\n addConnector(this);\n }\n }\n\n static create(options: NgwConnectorOptions): NgwConnector {\n return new this(options);\n }\n\n /**\n * Fast way to specify the connection address to NextGIS Web.\n * The current connection will be severed.\n * @param baseUrl - NGW url\n */\n setNgw(baseUrl: string): void {\n this.logout();\n this.options.baseUrl = baseUrl;\n addConnector(this);\n }\n\n /**\n * Establishing a connection with NextGIS Web to fulfill all other requests.\n * @remarks\n * This method need not be called manually as it is used when forming a request in {@link NgwConnector.apiRequest | apiRequest}.\n * Can be used to check connection.\n * @example\n * ```javascript\n * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});\n * connector.connect()\n * .then(() => console.log('Ok'))\n * .catch((er) => console.log('Connection problem', er));\n * ```\n */\n connect(): CancelablePromise<PyramidRoute> {\n const cache = new Cache();\n const auth = this.options.auth;\n const makeConnect = () =>\n new CancelablePromise((resolve, reject) => {\n const makeQuery = () => {\n return this.makeQuery(this.routeStr, {}, {})\n .then((route: PyramidRoute) => {\n resolve(route);\n })\n .catch((er) => {\n reject(er);\n });\n };\n if (auth) {\n const { login, password } = auth;\n if (login && password) {\n return this.getUserInfo({ login, password })\n .then(() => {\n makeQuery();\n })\n .catch((er) => reject(er));\n }\n }\n return makeQuery();\n });\n return cache.add('route', makeConnect, {\n id: this.id,\n auth,\n baseUrl: this.options.baseUrl,\n });\n }\n\n /**\n * Quick way to change NextGIS Web user.\n * @param credentials - New user credentials\n */\n login(credentials: Credentials): CancelablePromise<UserInfo> {\n this.logout();\n addConnector(this);\n return this.getUserInfo(credentials);\n }\n\n /**\n * Disconnecting a user. Aborting all current requests\n */\n logout(): void {\n removeConnector(this);\n this.options.auth = undefined;\n this.user = undefined;\n this.emitter.emit('logout');\n this.resources.cache.clean();\n }\n\n getUserInfo(credentials?: Credentials): CancelablePromise<UserInfo> {\n if (this.user && this.user.id) {\n return CancelablePromise.resolve(this.user);\n }\n if (credentials) {\n this.options.auth = credentials;\n }\n const options: RequestOptions = {\n headers: this.getAuthorizationHeaders(credentials),\n // withCredentials: true\n };\n\n // Do not use request('auth.current_user') to avoid circular-references\n return this.makeQuery('/api/component/auth/current_user', {}, options)\n .then((data: UserInfo) => {\n this.user = data;\n this.emitter.emit('login', data);\n return data;\n })\n .catch((er) => {\n this.emitter.emit('login:error', er);\n throw er;\n });\n }\n\n /**\n * Obtaining the required Headers for authentication of requests in the NGW.\n */\n getAuthorizationHeaders(\n credentials?: Credentials,\n ): RequestHeaders | undefined {\n const client = this.makeClientId(credentials);\n if (client) {\n return {\n Authorization: 'Basic ' + client,\n };\n }\n }\n\n makeClientId(credentials?: Credentials): string | undefined {\n credentials = credentials || this.options.auth;\n if (credentials) {\n const { login, password } = credentials;\n const str = unescape(encodeURIComponent(`${login}:${password}`));\n // @ts-ignore\n if (__BROWSER__) {\n return window.btoa(str);\n } else {\n return Buffer.from(str).toString('base64');\n }\n }\n }\n\n /**\n * Send request to NGW api router.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param params - Request item params or query params\n * @param requestOptions - Request options\n *\n * @example\n * ```javascript\n *\n * // there is such an NGW route item\n * // \"feature_layer.feature.item\": [\n * // \"/api/resource/{0}/feature/{1}\",\n * // \"id\",\n * // \"fid\"\n * // ],\n *\n * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });\n * connector.apiRequest('feature_layer.feature.item', {\n * // request params for {0} and {1}\n * 'id': 2011,\n * 'fid': 101,\n * // query params\n * 'srs': 4326,\n * 'geom_format': 'geojson',\n * }, { method: 'GET' });\n * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'\n *\n * ```\n */\n apiRequest<\n K extends keyof RequestItemsParamsMap,\n P extends RequestItemKeys = RequestItemKeys,\n >(\n name: K,\n params_: RequestItemsParams<K> = {},\n requestOptions: RequestOptions = {},\n ): CancelablePromise<P[K]> {\n const { method, headers, withCredentials, responseType } = requestOptions;\n const params = objectRemoveEmpty(params_);\n const makeApiRequest = () =>\n apiRequest({ name, params, requestOptions, connector: this });\n if (requestOptions.cache && method === 'GET') {\n const cache = new Cache<CancelablePromise<P[K]>>();\n return cache.add(name, makeApiRequest, {\n params,\n ...objectRemoveEmpty({\n headers,\n withCredentials,\n responseType,\n baseUrl: this.options.baseUrl,\n auth: this.options.auth,\n }),\n });\n }\n return makeApiRequest();\n }\n\n /**\n * Shortcut method for send POST request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n *\n * @example\n * ```javascript\n * connector.post('resource.collection', { data: POST_PAYLOAD })\n * .then((newResource) => console.log(newResource))\n * .catch((error) => console.warn(error));\n * ```\n */\n post<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions<'POST'>,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<PostRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'POST';\n return this.apiRequest<K, PostRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send GET request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n get<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions | undefined | null,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<GetRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'GET';\n return this.apiRequest<K, GetRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send PATCH request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n patch<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<PatchRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'PATCH';\n return this.apiRequest<K, PatchRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send PUT request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n put<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<PutRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'PUT';\n return this.apiRequest<K, PutRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send DELETE request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n delete<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions | undefined | null,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<DeleteRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'DELETE';\n return this.apiRequest<K, DeleteRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Send request to NGW.\n * @param url - URL address to NGW\n * @param params - Query params\n * @param options - Request options\n */\n makeQuery(\n url: string,\n params?: Params,\n options: RequestOptions = {},\n ): CancelablePromise<any> {\n url = (this.options.baseUrl ? this.options.baseUrl : '') + url;\n if (url) {\n if (params) {\n url = template(url, params);\n }\n // remove double slash\n url = fixUrlStr(url);\n return this._loadData(encodeURI(url), options);\n } else {\n throw new Error('Empty `url` not allowed');\n }\n }\n\n // -------------------------------------------------------------------------\n // Resource Methods\n // -------------------------------------------------------------------------\n\n /**\n * {@inheritDoc ResourcesControl.getOne}\n */\n getResource(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getOneOrFail}\n */\n getResourceOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem> {\n return this.resources.getOneOrFail(resource, requestOptions);\n }\n\n /**\n * @deprecated - use {@link NgwConnector.getResource}\n */\n getResourceBy(\n resource: DeepPartial<Resource>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(resource);\n }\n\n /**\n * @deprecated - use {@link NgwConnector.getResource}\n */\n getResourceByKeyname(\n keyname: string,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(keyname);\n }\n\n /**\n * @deprecated - use {@link NgwConnector.getResource}\n */\n getResourceById(id: number): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(id);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getId}\n */\n getResourceId(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number | undefined> {\n return this.resources.getId(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getIdOrFail}\n */\n getResourceIdOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number> {\n return this.resources.getIdOrFail(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getMany}\n */\n getResourcesBy(\n resource: DeepPartial<Resource>,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem[]> {\n return this.resources.getMany(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getParent}\n */\n getResourceParent(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getParent(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getChildrenOf}\n */\n getResourceChildren(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem[]> {\n return this.resources.getChildrenOf(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.update}\n */\n updateResource(\n resource: ResourceIdKeynameDef,\n data: DeepPartial<ResourceItem>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.update(resource, data);\n }\n\n /**\n * {@inheritDoc ResourcesControl.delete}\n */\n deleteResource(resource: ResourceIdKeynameDef): CancelablePromise<void> {\n return this.resources.delete(resource);\n }\n\n /**\n * @internal\n */\n protected _loadData(\n url: string,\n options: RequestOptions,\n ): CancelablePromise<any> {\n options.responseType = options.responseType || 'json';\n return new CancelablePromise((resolve, reject, onCancel) => {\n if (this.user) {\n options = options || {};\n // options.withCredentials = true;\n options.headers = {\n ...this.getAuthorizationHeaders(),\n ...options.headers,\n };\n }\n loadData(url, resolve, options, reject, onCancel);\n }).catch((httpError) => {\n if (httpError instanceof CancelablePromise.CancelError) {\n // not need to handle cancel error because onCancel method is used\n } else {\n // @ts-ignore\n if (__DEV__) {\n console.warn('DEV WARN', httpError);\n }\n const er = this._handleHttpError(httpError);\n if (er) {\n throw er;\n }\n }\n });\n }\n\n private _handleHttpError(er: Error) {\n if (er) {\n if (er instanceof NgwError) {\n if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {\n throw new ResourceNotFoundError(er);\n } else if (\n er.exception === 'nextgisweb.core.exception.InsufficientPermissions'\n ) {\n throw new InsufficientPermissionsError(er);\n }\n }\n }\n return er;\n }\n}\n","import CancelablePromise from '@nextgis/cancelable-promise';\nimport { template } from './template';\nimport type { NgwConnector } from '../NgwConnector';\nimport type {\n RequestItemKeys,\n RequestItemsParams,\n RequestOptions,\n} from '../interfaces';\nimport type { RequestItemsParamsMap } from '../types/RequestItemsParamsMap';\n\ninterface ApiRequestOptions<K extends keyof RequestItemsParamsMap> {\n name: string;\n connector: NgwConnector;\n params: RequestItemsParams<K>;\n requestOptions: RequestOptions;\n}\n\nexport function apiRequest<\n K extends keyof RequestItemsParamsMap,\n P extends RequestItemKeys = RequestItemKeys,\n>(opt: ApiRequestOptions<K>): CancelablePromise<P[K]> {\n const params = opt.params;\n return new CancelablePromise((resolve, reject) => {\n opt.connector\n .connect()\n .then((apiItems) => {\n let apiItem = apiItems && apiItems[opt.name];\n if (apiItem) {\n apiItem = [...apiItem];\n let url = apiItem.shift();\n if (apiItem.length) {\n const replaceParams: {\n [num: number]: string;\n } = {};\n for (let fry = 0; fry < apiItem.length; fry++) {\n const arg = apiItem[fry];\n replaceParams[fry] = '{' + arg + '}';\n if (params[arg] === undefined) {\n throw new Error(\n '`' + arg + '`' + ' url api argument is not specified',\n );\n }\n }\n if (url) {\n url = template(url, replaceParams);\n }\n }\n // Transfer part of the parameters from `params` to the URL string\n if (params) {\n const paramArray = [];\n const paramList = params.paramList;\n if (Array.isArray(paramList)) {\n delete params.paramList;\n paramList.forEach((x) => {\n paramArray.push(`${x[0]}=${x[1]}`);\n });\n }\n for (const p in params) {\n if (apiItem.indexOf(p) === -1) {\n paramArray.push(`${p}=${params[p]}`);\n }\n }\n if (paramArray.length) {\n url = url + '?' + paramArray.join('&');\n }\n }\n if (url) {\n resolve(opt.connector.makeQuery(url, params, opt.requestOptions));\n } else {\n reject(new Error('request url is not set'));\n }\n } else {\n resolve(undefined);\n }\n })\n .catch((er) => {\n reject(er);\n });\n });\n}\n","/**\n * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API\n *\n * @remarks\n * 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.\n *\n * @packageDocumentation\n * @module ngw-connector\n */\nimport { NgwConnector } from './NgwConnector';\n\nexport * from './interfaces';\nexport * from './types/ResourceItem';\nexport * from './types/FeatureLayer';\nexport * from './types/RequestItemsParamsMap';\nexport * from './types/ResourceStore';\n\n// export { NgwConnector };\nexport default NgwConnector;\n"],"names":["NgwError","Error","constructor","er","super","this","Object","assign","setPrototypeOf","prototype","NetworkError","url","message","location","origin","loadData","callback","options","error","onCancel","method","xhr","XMLHttpRequest","open","responseType","getResponseText","JSON","parse","responseText","onload","indexOf","status","forError","cb","response","processingResponse","onerror","upload","onprogress","e","lengthComputable","percentComplete","loaded","total","onProgress","headers","h","header","setRequestHeader","data","undefined","withCredentials","file","FormData","append","d","stringify","abort","send","templateRe","template","str","replace","s","key","value","ResourceNotFoundError","obj","InsufficientPermissionsError","CONNECTORS","addConnector","connector","push","isObject","val","toString","call","exclude","resourceToQuery","resource","prefix","query","entries","children","parent_id","id","defined","ResourcesControl","Cache","getOne","requestOptions","cache","forCache","opt","keyname","addFull","_fetchResourceBy","_fetchResourceById","CancelablePromise","resolve","getOneOrFail","then","res","getId","getIdOrFail","resp","getMany","_resourceCacheFilter","items","length","get","serialization","resources","x","add","getParent","child","parent","getChildrenOf","i","update","put","delete","_cleanResourceItemCache","all","toDelete","c","cid","includes","catch","matchAll","filter","objectDeepEqual","ID","NgwConnector","EventEmitter","exist","find","baseUrl","auth","findConnector","route","routeStr","create","setNgw","logout","connect","reject","makeQuery","login","password","getUserInfo","credentials","index","splice","removeConnector","user","emitter","emit","clean","getAuthorizationHeaders","client","makeClientId","Authorization","unescape","encodeURIComponent","window","btoa","apiRequest","name","params_","params","objectRemoveEmpty","makeApiRequest","apiItems","apiItem","shift","replaceParams","fry","arg","paramArray","paramList","Array","isArray","forEach","p","join","post","patch","fixUrlStr","_loadData","encodeURI","getResource","getResourceOrFail","getResourceBy","getResourceByKeyname","getResourceById","getResourceId","getResourceIdOrFail","getResourcesBy","getResourceParent","getResourceChildren","updateResource","deleteResource","httpError","CancelError","console","warn","_handleHttpError","exception"],"mappings":"yNAKaA,UAAiBC,MAW5BC,YAAYC,GACVC,QAXFC,UAAO,WAYLC,OAAOC,OAAOF,KAAMF,GACpBG,OAAOE,eAAeH,KAAML,EAASS,kBChB5BC,UAAqBT,MAGhCC,YAAYS,GACVP,QAHFC,UAAO,eAILC,OAAOE,eAAeH,KAAMK,EAAaD,WACzCJ,KAAKO,QAAU,qBAAqBD,uFAC0CE,SAASC,UCqB3F,IAAIC,EAGFA,EAAW,CACTJ,EACAK,EACAC,EAA6B,GAC7BC,EACAC,KAEAF,EAAQG,OAASH,EAAQG,QAAU,MAEnC,MAAMC,EAAM,IAAIC,eAChBD,EAAIE,KAAKN,EAAQG,QAAU,MAAOT,GAAK,GAEV,SAAzBM,EAAQO,eACVH,EAAIG,aAAeP,EAAQO,cAE7B,MAAMC,EAAkB,KACtB,IACE,OAAOC,KAAKC,MAAMN,EAAIO,cACtB,MAAOzB,GACP,OAAOkB,EAAIO,eAefP,EAAIQ,OAAS,MACuC,IAA9C,CAAC,IAAK,IAAK,IAAK,KAAKC,QAAQT,EAAIU,SACnCb,EAAM,IAAIlB,EAASyB,MAdI,EAACO,GAAW,KACrC,MAAMC,EAAKD,EAAWd,EAAQF,EACD,SAAzBC,EAAQO,aACVS,EAAGZ,EAAIa,UAEHb,EAAIO,aACNK,EAAGR,KAEHP,EAAM,CAAEN,QAAS,MAQrBuB,IAoBFd,EAAIe,QAAWjC,IAEXe,EADiB,IAAfG,EAAIU,OACA,IAAIrB,EAAaC,GAEj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W,GAEA,OAAOrF,KAAK2G,UAAUT,MAAMxB,EAAUW,GAMxC4G,oBACEvH,EACAW,GAEA,OAAOrF,KAAK2G,UAAUR,YAAYzB,EAAUW,GAM9C6G,eACExH,EACAW,GAEA,OAAOrF,KAAK2G,UAAUN,QAAQ3B,EAAUW,GAM1C8G,kBACEzH,EACAW,GAEA,OAAOrF,KAAK2G,UAAUG,UAAUpC,EAAUW,GAM5C+G,oBACE1H,EACAW,GAEA,OAAOrF,KAAK2G,UAAUM,cAAcvC,EAAUW,GAMhDgH,eACE3H,EACA9B,GAEA,OAAO5C,KAAK2G,UAAUQ,OAAOzC,EAAU9B,GAMzC0J,eAAe5H,GACb,OAAO1E,KAAK2G,UAAUU,OAAO3C,GAMrB+G,UACRnL,EACAM,GAGA,OADAA,EAAQO,aAAeP,EAAQO,cAAgB,OACxC,IAAI0E,GAAkB,CAACC,EAASgD,EAAQhI,KACzCd,KAAKuJ,QACP3I,EAAUA,GAAW,IAEb4B,QAAU,IACbxC,KAAK2J,6BACL/I,EAAQ4B,UAGf9B,EAASJ,EAAKwF,EAASlF,EAASkI,EAAQhI,MACvC8G,OAAO2E,IACR,GAAIA,aAAqB1G,EAAkB2G,iBAEpC,sCAGHC,QAAQC,KAAK,WAAYH,GAE3B,MAAMzM,EAAKE,KAAK2M,iBAAiBJ,GACjC,GAAIzM,EACF,MAAMA,MAMN6M,iBAAiB7M,GACvB,GAAIA,GACEA,aAAcH,EAAU,CAC1B,GAAqB,mDAAjBG,EAAG8M,UACL,MAAM,IAAI/I,EAAsB/D,GAC3B,GACY,sDAAjBA,EAAG8M,UAEH,MAAM,IAAI7I,EAA6BjE,GAI7C,OAAOA,GA/fFmI,SAAS,CACdtI,SAAAA,EACAkE,sBAAAA,GE5BJ,MAAeoE"}
|
|
1
|
+
{"version":3,"file":"ngw-connector.esm-bundler.prod.js","sources":["../src/errors/NgwError.ts","../src/errors/NetworkError.ts","../src/utils/isObject.ts","../src/utils/loadData.ts","../src/utils/template.ts","../src/errors/ResourceNotFoundError.ts","../src/errors/InsufficientPermissionsError.ts","../src/activeConnectors.ts","../src/utils/resourceToQuery.ts","../src/ResourcesControl.ts","../src/utils/resourceCompare.ts","../src/NgwConnector.ts","../src/utils/apiRequest.ts","../src/index.ts"],"sourcesContent":["import { NgwExceptions } from '../interfaces';\n\n/**\n * Thrown when...\n */\nexport class NgwError extends Error {\n name = 'NgwError';\n\n title!: string;\n message!: string;\n detail!: string;\n exception!: NgwExceptions;\n status_code!: number | 404 | 500;\n data?: Record<string, any>;\n guru_meditation!: string;\n\n constructor(er?: NgwError) {\n super();\n Object.assign(this, er);\n Object.setPrototypeOf(this, NgwError.prototype);\n }\n}\n","/**\n * Thrown when...\n */\nexport class NetworkError extends Error {\n name = 'NetworkError';\n\n constructor(url: string) {\n super();\n Object.setPrototypeOf(this, NetworkError.prototype);\n this.message = `Unable to request ${url}.\n Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors\n }\n}\n","export function isObject(val: unknown): val is Record<string | number, any> {\n return Object.prototype.toString.call(val) === '[object Object]';\n}\n","import {\n RequestOptions as NgwRequestOptions,\n RequestMethods,\n} from '../interfaces';\nimport { NgwError } from '../errors/NgwError';\nimport { NetworkError } from '../errors/NetworkError';\nimport { isObject } from './isObject';\n\n// readyState\n// Holds the status of the XMLHttpRequest.\n// 0: request not initialized\n// 1: server connection established\n// 2: request received\n// 3: processing request\n// 4: request finished and response is ready\n\n// status\n// 200: \"OK\"\n// 201 \"Created\"\tThe request has been fulfilled, and a new resource is created\n// 403: \"Forbidden\"\n// 404: \"Page not found\"\n// 500: \"Internal Server Error\"\n// For a complete list go to the Http Messages Reference\n\ntype LoadData = (\n url: string,\n callback: (...args: any[]) => any,\n options: NgwRequestOptions<RequestMethods> | undefined,\n error: (reason?: any) => void,\n onCancel: (cancelHandler: () => void) => void,\n) => void;\n\nlet loadData: LoadData;\n// @ts-ignore\nif (__BROWSER__) {\n loadData = (\n url: string,\n callback: (...args: any[]) => any,\n options: NgwRequestOptions = {},\n error: (reason?: any) => void,\n onCancel: (cancelHandler: () => void) => void,\n ): void => {\n options.method = options.method || 'GET';\n\n const xhr = new XMLHttpRequest();\n xhr.open(options.method || 'GET', url, true); // true for asynchronous\n\n if (options.responseType === 'blob') {\n xhr.responseType = options.responseType;\n }\n const getResponseText = () => {\n try {\n return JSON.parse(xhr.responseText);\n } catch (er) {\n return xhr.responseText;\n }\n };\n const processingResponse = (forError = false) => {\n const cb = forError ? error : callback;\n if (options.responseType === 'blob') {\n cb(xhr.response);\n } else {\n if (xhr.responseText) {\n cb(getResponseText());\n } else {\n error({ message: '' });\n }\n }\n };\n xhr.onload = () => {\n if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {\n error(new NgwError(getResponseText()));\n }\n processingResponse();\n };\n\n // xhr.onreadystatechange = () => {\n // if (\n // (xhr.readyState === 4 && xhr.status === 200) ||\n // (xhr.readyState === 3 && xhr.status === 201)\n // ) {\n // processingResponse();\n // } else if (xhr.readyState === 3 && xhr.status === 400) {\n // processingResponse();\n // } else if (xhr.readyState === 4 && xhr.status === 500) {\n // processingResponse();\n // } else if (xhr.readyState === 4 && xhr.status === 401) {\n // error(xhr.statusText);\n // } else if (xhr.readyState === 4) {\n // error('request error');\n // }\n // };\n\n xhr.onerror = (er) => {\n if (xhr.status === 0) {\n error(new NetworkError(url));\n } else {\n error(er);\n }\n };\n\n xhr.upload.onprogress = function (e) {\n if (e.lengthComputable) {\n const percentComplete = (e.loaded / e.total) * 100;\n if (options.onProgress) {\n options.onProgress(percentComplete, e);\n }\n // console.log(percentComplete + '% uploaded');\n }\n };\n\n const headers = options.headers;\n if (headers) {\n for (const h in headers) {\n const header = headers[h];\n if (typeof header === 'string') {\n xhr.setRequestHeader(h, header);\n }\n }\n }\n if (options.withCredentials !== undefined) {\n xhr.withCredentials = options.withCredentials;\n }\n\n let data: FormData | any;\n if (options.file) {\n data = new FormData();\n data.append('file', options.file);\n if (options.data) {\n for (const d in options.data) {\n data.append(d, data[d]);\n }\n }\n } else {\n data = options.data\n ? typeof options.data === 'string'\n ? options.data\n : JSON.stringify(options.data)\n : null;\n }\n if (onCancel) {\n onCancel(() => {\n xhr.abort();\n });\n }\n xhr.send(data);\n };\n} else {\n const url = require('url');\n const http = require('http');\n const https = require('https');\n const FormData = require('form-data');\n\n const adapterFor = (inputUrl: string) => {\n const adapters: Record<string, any> = {\n 'http:': http,\n 'https:': https,\n };\n const protocol = url.parse(inputUrl).protocol || 'https:';\n return adapters[protocol];\n };\n\n loadData = (\n url: string,\n callback: (...args: any[]) => any,\n options: NgwRequestOptions<RequestMethods> = {},\n error: (reason?: any) => void,\n onCancel: (cancelHandler: () => void) => void,\n ): Promise<unknown> => {\n const { file, headers, method, data, responseType } = options;\n\n const request = new Promise((resolve, reject) => {\n const adapter = adapterFor(url);\n if (adapter) {\n const requestOpt = {\n headers: headers || {},\n method,\n };\n const body = typeof data === 'string' ? data : JSON.stringify(data);\n // https://stackoverflow.com/questions/35589109/node-http-delete-request-no-longer-works-after-upgrading-from-0-10-40\n let form;\n let uploadedFile = file;\n if (file) {\n const fileMeta = {};\n if (\n isObject(file) &&\n 'file' in file &&\n ('filename' in file || 'name' in file)\n ) {\n const {\n file: file_,\n name,\n ...fileMeta_\n } = file as Record<string, any>;\n if (name && !fileMeta_.filename) {\n fileMeta_.filename = name;\n }\n Object.assign(fileMeta, fileMeta_);\n uploadedFile = file_ as File;\n }\n form = new FormData();\n form.append('file', uploadedFile, fileMeta);\n if (data) {\n for (const d in data) {\n form.append(d, data[d]);\n }\n }\n Object.assign(requestOpt.headers, {\n // 'content-length': form.getLengthSync(),\n ...form.getHeaders(),\n });\n }\n if (body !== undefined && method !== 'POST') {\n Object.assign(requestOpt.headers, {\n 'content-type': 'application/json',\n 'content-length': Buffer.byteLength(body),\n });\n }\n const req = adapter.request(url, requestOpt, (resp: any) => {\n let data = '';\n resp.on('data', (chunk: any) => {\n data += chunk;\n });\n resp.on('end', () => {\n if (data) {\n if (responseType === 'blob') {\n resolve(data);\n } else {\n let json: Record<string, any> | undefined;\n try {\n json = JSON.parse(data);\n if (json && json.status_code && json.status_code) {\n reject(json.message);\n }\n } catch (er) {\n reject(er);\n // throw new Error(er);\n }\n if (json !== undefined) {\n resolve(json);\n }\n }\n }\n reject('no data');\n });\n });\n if (form) {\n form.pipe(req);\n }\n req.on('error', (err: any) => {\n reject(err);\n });\n if (body) {\n req.write(body);\n }\n onCancel(() => {\n req.abort();\n });\n req.end();\n } else {\n throw new Error(`Given URL '${url}' is not correct`);\n }\n });\n return request\n .then((data) => {\n if (callback) {\n callback(data);\n }\n return data;\n })\n .catch((er) => {\n if (error) {\n error(er);\n } else {\n throw new Error(er);\n }\n });\n };\n}\n\nexport { loadData };\n","// https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165\nconst templateRe = /\\{ *([\\w_-]+) *\\}/g;\n\nexport function template(str: string, data: { [param: string]: any }): string {\n return str.replace(templateRe, (s, key) => {\n let value = data[key];\n\n if (value === undefined) {\n throw new Error('No value provided for letiable ' + s);\n } else if (typeof value === 'function') {\n value = value(data);\n }\n return value;\n });\n}\n","import { NgwError } from './NgwError';\nimport { NgwExceptions } from '../interfaces';\n\n/**\n * Thrown when ...\n */\nexport class ResourceNotFoundError extends NgwError {\n name = 'ResourceNotFoundError';\n exception: NgwExceptions = 'nextgisweb.resource.exception.ResourceNotFound';\n\n constructor(obj?: ResourceNotFoundError) {\n super(obj);\n Object.setPrototypeOf(this, ResourceNotFoundError.prototype);\n }\n}\n","import { NgwError } from './NgwError';\nimport { NgwExceptions } from '../interfaces';\n\n/**\n * Thrown when ...\n */\nexport class InsufficientPermissionsError extends NgwError {\n name = 'InsufficientPermissionsError';\n exception: NgwExceptions =\n 'nextgisweb.core.exception.InsufficientPermissions';\n\n constructor(obj: InsufficientPermissionsError) {\n super(obj);\n Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);\n }\n}\n","import { NgwConnectorOptions } from './interfaces';\nimport { NgwConnector } from './NgwConnector';\nimport { objectDeepEqual } from '@nextgis/utils';\n\nexport const CONNECTORS: NgwConnector[] = [];\n\nexport function addConnector(connector: NgwConnector): void {\n CONNECTORS.push(connector);\n}\n\nexport function findConnector(\n options: NgwConnectorOptions,\n): NgwConnector | undefined {\n return CONNECTORS.find((x) => {\n if (x.options.baseUrl === options.baseUrl) {\n if (options.auth) {\n if (x.options.auth) {\n return objectDeepEqual(x.options.auth, options.auth);\n }\n } else {\n // if auth not in find options; use first connector with same url\n return true;\n }\n }\n });\n}\n\nexport function removeConnector(connector: NgwConnector): void {\n const index = CONNECTORS.indexOf(connector);\n if (index !== -1) {\n CONNECTORS.splice(index, 1);\n }\n}\n\nexport function findAndRemoveConnector(options: NgwConnectorOptions): void {\n const exist = findConnector(options);\n if (exist) {\n removeConnector(exist);\n }\n}\n","import { DeepPartial, defined } from '@nextgis/utils';\nimport { Resource } from '../types/ResourceItem';\nimport { isObject } from './isObject';\n\nconst exclude = ['description'];\n\n/**\n * @remarks\n * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources\n *\n * ```\n * { keyname, owner_user: { id }} > { keyname, owner_user__id }\n * ```\n *\n * @param resource - Any property from NGW resource item\n */\nexport function resourceToQuery(\n resource: DeepPartial<Resource>,\n prefix = '',\n): Record<string, unknown> {\n prefix = prefix ? prefix + '__' : '';\n const query: Record<string, any> = {};\n for (const [key, value] of Object.entries(resource)) {\n if (exclude.indexOf(key) === -1) {\n if (isObject(value)) {\n if (key === 'owner_user') {\n const children = resourceToQuery(value as DeepPartial<Resource>, key);\n Object.assign(query, children);\n } else if (key === 'parent' && 'id' in value) {\n query.parent_id = value.id;\n }\n } else if (defined(value)) {\n query[prefix + key] = value;\n }\n }\n }\n return query;\n}\n","import CancelablePromise from '@nextgis/cancelable-promise';\nimport { defined } from '@nextgis/utils';\nimport Cache from '@nextgis/cache';\n\nimport { resourceToQuery } from './utils/resourceToQuery';\nimport { resourceCompare } from './utils/resourceCompare';\nimport { ResourceNotFoundError } from './errors/ResourceNotFoundError';\n\nimport { isObject } from './utils/isObject';\n\nimport type { DeepPartial } from '@nextgis/utils';\nimport type { NgwConnector } from './NgwConnector';\nimport type { ResourceItem, Resource } from './types/ResourceItem';\nimport type { RequestOptions, ResourceDefinition } from './interfaces';\n\nexport class ResourcesControl {\n cache = new Cache<\n CancelablePromise<ResourceItem | undefined>,\n { id?: number | string }\n >();\n\n constructor(private connector: NgwConnector) {}\n\n // -------------------------------------------------------------------------\n // Resource Methods\n // -------------------------------------------------------------------------\n\n /**\n * Receive resource from NGW by id, keyname or search-object parameter.\n * @param resource - Resource id, keyname or search-object\n *\n * @remarks\n * Fetching resource would be cached to speed up next call\n */\n getOne(\n resource: ResourceDefinition,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem | undefined> {\n const cache = new Cache();\n const forCache: { keyname?: string; id?: number } = {};\n const opt = { ...requestOptions, cache: false };\n if (typeof resource === 'string') {\n forCache.keyname = resource;\n } else if (typeof resource === 'number') {\n forCache.id = resource;\n } else if (isObject(resource)) {\n forCache.id = resource.id;\n }\n const makeRequest = () => {\n if (typeof resource === 'string') {\n return this._fetchResourceBy({ keyname: resource }, opt);\n } else if (typeof resource === 'number') {\n return this._fetchResourceById(resource, opt);\n } else if (isObject(resource)) {\n return this._fetchResourceBy(resource, opt);\n }\n return CancelablePromise.resolve(undefined);\n };\n\n return cache.addFull('resource', makeRequest, forCache);\n }\n\n getOneOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem> {\n return this.getOne(resource, requestOptions).then((res) => {\n if (res) {\n return res;\n }\n throw new ResourceNotFoundError();\n });\n }\n\n /**\n * A fast way to retrieve resource ID for any resource definition.\n * @param resource - Any available resource definition\n *\n * @remarks\n * There are situations when exactly the resource id is needed\n * (for example, to compose the correct request to the api)\n * then this method will come in handy to facilitate the extraction of the identifier\n * if the resource is specified through a keyname or other parameters.\n */\n getId(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number | undefined> {\n if (typeof resource === 'number') {\n return CancelablePromise.resolve(resource);\n } else if (typeof resource === 'string' || isObject(resource)) {\n return this.getOne(resource, requestOptions).then((res) => {\n if (res) {\n return res.resource.id;\n }\n });\n }\n return CancelablePromise.resolve(undefined);\n }\n\n /**\n * A fast way to retrieve resource ID for any resource definition.\n * @param resource - Any available resource definition\n *\n * @remarks\n * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.\n * To not make one more checks if the resource is definitely exists\n */\n getIdOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number> {\n return this.getId(resource, requestOptions).then((resp) => {\n if (resp === undefined) {\n throw new Error();\n }\n return resp;\n });\n }\n\n getMany(\n resource: DeepPartial<Resource>,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem[]> {\n return this._resourceCacheFilter(resource).then((items) => {\n if (!items.length) {\n const query: Record<string, unknown> = {};\n if (resource.keyname) {\n query.keyname = resource.keyname;\n } else {\n Object.assign(query, resourceToQuery(resource));\n }\n return this.connector\n .get('resource.search', requestOptions, {\n serialization: 'full',\n ...query,\n })\n .then((resources) => {\n if (resources) {\n for (const x of resources) {\n this.cache.add('resource.item', CancelablePromise.resolve(x), {\n id: x.resource.id,\n });\n }\n }\n return resources;\n });\n }\n return items;\n });\n }\n\n getParent(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.getOne(resource, requestOptions).then((child) => {\n if (child) {\n return this.getOne(child.resource.parent.id, requestOptions);\n }\n return CancelablePromise.resolve(undefined);\n });\n }\n\n getChildrenOf(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem[]> {\n return this.getId(resource).then((parent) => {\n return this.connector\n .get(\n 'resource.collection',\n { cache: true, ...requestOptions },\n {\n parent,\n },\n )\n .then((items) => {\n for (const i of items) {\n this.cache.add('resource.item', CancelablePromise.resolve(i), {\n id: i.resource.id,\n });\n }\n return items;\n });\n });\n }\n\n update(\n resource: ResourceDefinition,\n data: DeepPartial<ResourceItem>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.getId(resource).then((id) => {\n if (id !== undefined) {\n return this.connector.put('resource.item', { data }, { id });\n }\n });\n }\n\n /**\n * Fast way to delete resource from NGW and clean cache.\n * @param resource - Resource definition\n */\n delete(resource: ResourceDefinition): CancelablePromise<void> {\n return this.getId(resource).then((id) => {\n if (id !== undefined) {\n return this.connector.delete('resource.item', null, { id }).then(() => {\n this._cleanResourceItemCache(id);\n return undefined;\n });\n }\n });\n }\n\n private async _cleanResourceItemCache(id: number) {\n const all = this.cache.all();\n const toDelete: typeof all = [];\n for (const c of all) {\n const cid = c.options && c.options.id;\n if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {\n if (typeof cid === 'number') {\n if (cid === id) {\n toDelete.push(c);\n }\n } else {\n const rid = await this.getId(cid);\n if (rid === id) {\n toDelete.push(c);\n }\n }\n }\n }\n for (const d of toDelete) {\n this.cache.delete(d);\n }\n }\n\n private _fetchResourceById(\n id: number,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem | undefined> {\n const promise = () =>\n this.connector.get('resource.item', requestOptions, { id });\n\n return this.cache\n .add('resource.item', promise, {\n id,\n })\n .catch((er) => {\n if (!(er instanceof ResourceNotFoundError)) {\n throw er;\n }\n return undefined;\n });\n }\n\n private _fetchResourceBy(\n resource: DeepPartial<Resource>,\n requestOptions?: RequestOptions,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.getMany(resource, requestOptions).then((resources) => {\n return resources[0];\n });\n }\n\n private _resourceCacheFilter(\n resource: DeepPartial<Resource>,\n ): CancelablePromise<ResourceItem[]> {\n return CancelablePromise.all(this.cache.matchAll('resource.item')).then(\n (resources) => {\n const items: ResourceItem[] = [];\n resources.filter((x) => {\n if (x) {\n // identical by uniq props\n if (resource.keyname && x.resource.keyname) {\n return resource.keyname === x.resource.keyname;\n }\n if (defined(resource.id) && defined(x.resource.id)) {\n return resource.id === x.resource.id;\n }\n return resourceCompare(resource, x.resource);\n }\n });\n return items;\n },\n );\n }\n}\n","import { objectDeepEqual } from '@nextgis/utils';\nimport type { DeepPartial } from '@nextgis/utils';\nimport type { Resource } from '../types/ResourceItem';\n\nexport function resourceCompare(\n res1: DeepPartial<Resource>,\n res2: DeepPartial<Resource>,\n): boolean {\n return objectDeepEqual(res1, res2);\n}\n","import { EventEmitter } from 'events';\nimport CancelablePromise from '@nextgis/cancelable-promise';\nimport { objectRemoveEmpty } from '@nextgis/utils';\nimport { fixUrlStr } from '@nextgis/utils';\nimport Cache from '@nextgis/cache';\n\nimport { loadData } from './utils/loadData';\nimport { template } from './utils/template';\nimport { NgwError } from './errors/NgwError';\nimport { ResourceNotFoundError } from './errors/ResourceNotFoundError';\nimport { InsufficientPermissionsError } from './errors/InsufficientPermissionsError';\nimport {\n addConnector,\n findConnector,\n removeConnector,\n} from './activeConnectors';\nimport { ResourcesControl } from './ResourcesControl';\n\nimport type { DeepPartial } from '@nextgis/utils';\nimport type {\n DeleteRequestItemsResponseMap,\n PatchRequestItemsResponseMap,\n PostRequestItemsResponseMap,\n GetRequestItemsResponseMap,\n PutRequestItemsResponseMap,\n ResourceIdKeynameDef,\n NgwConnectorOptions,\n ResourceDefinition,\n RequestItemsParams,\n RequestItemKeys,\n RequestHeaders,\n RequestOptions,\n PyramidRoute,\n Credentials,\n UserInfo,\n Params,\n} from './interfaces';\nimport type { RequestItemsParamsMap } from './types/RequestItemsParamsMap';\nimport type { ResourceItem, Resource } from './types/ResourceItem';\nimport { apiRequest } from './utils/apiRequest';\n\nlet ID = 0;\n\nexport class NgwConnector {\n static errors = {\n NgwError,\n ResourceNotFoundError,\n };\n id = ID++;\n\n emitter = new EventEmitter();\n user?: UserInfo;\n\n resources!: ResourcesControl;\n\n private routeStr = '/api/component/pyramid/route';\n\n constructor(public options: NgwConnectorOptions) {\n const exist = findConnector(options);\n if (exist) {\n return exist;\n } else {\n if (this.options.route) {\n this.routeStr = this.options.route;\n }\n this.resources = new ResourcesControl(this);\n addConnector(this);\n }\n }\n\n static create(options: NgwConnectorOptions): NgwConnector {\n return new this(options);\n }\n\n /**\n * Fast way to specify the connection address to NextGIS Web.\n * The current connection will be severed.\n * @param baseUrl - NGW url\n */\n setNgw(baseUrl: string): void {\n this.logout();\n this.options.baseUrl = baseUrl;\n addConnector(this);\n }\n\n /**\n * Establishing a connection with NextGIS Web to fulfill all other requests.\n * @remarks\n * This method need not be called manually as it is used when forming a request in {@link NgwConnector.apiRequest | apiRequest}.\n * Can be used to check connection.\n * @example\n * ```javascript\n * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});\n * connector.connect()\n * .then(() => console.log('Ok'))\n * .catch((er) => console.log('Connection problem', er));\n * ```\n */\n connect(): CancelablePromise<PyramidRoute> {\n const cache = new Cache();\n const auth = this.options.auth;\n const makeConnect = () =>\n new CancelablePromise((resolve, reject) => {\n const makeQuery = () => {\n return this.makeQuery<PyramidRoute>(this.routeStr, {}, {})\n .then((route) => {\n resolve(route);\n })\n .catch((er) => {\n reject(er);\n });\n };\n if (auth) {\n const { login, password } = auth;\n if (login && password) {\n return this.getUserInfo({ login, password })\n .then(() => {\n makeQuery();\n })\n .catch((er) => reject(er));\n }\n }\n return makeQuery();\n });\n return cache.add('route', makeConnect, {\n id: this.id,\n auth,\n baseUrl: this.options.baseUrl,\n });\n }\n\n /**\n * Quick way to change NextGIS Web user.\n * @param credentials - New user credentials\n */\n login(credentials: Credentials): CancelablePromise<UserInfo> {\n this.logout();\n addConnector(this);\n return this.getUserInfo(credentials);\n }\n\n /**\n * Disconnecting a user. Aborting all current requests\n */\n logout(): void {\n removeConnector(this);\n this.options.auth = undefined;\n this.user = undefined;\n this.emitter.emit('logout');\n this.resources.cache.clean();\n }\n\n getUserInfo(credentials?: Credentials): CancelablePromise<UserInfo> {\n if (this.user && this.user.id) {\n return CancelablePromise.resolve(this.user);\n }\n if (credentials) {\n this.options.auth = credentials;\n }\n const options: RequestOptions = {\n headers: this.getAuthorizationHeaders(credentials),\n // withCredentials: true\n };\n\n // Do not use apiRequest('auth.current_user') to avoid circular-references\n return this.makeQuery<UserInfo>(\n '/api/component/auth/current_user',\n {},\n options,\n )\n .then((data) => {\n this.user = data;\n this.emitter.emit('login', data);\n return data;\n })\n .catch((er) => {\n this.emitter.emit('login:error', er);\n throw er;\n });\n }\n\n /**\n * Obtaining the required Headers for authentication of requests in the NGW.\n */\n getAuthorizationHeaders(\n credentials?: Credentials,\n ): RequestHeaders | undefined {\n const client = this.makeClientId(credentials);\n if (client) {\n return {\n Authorization: 'Basic ' + client,\n };\n }\n }\n\n makeClientId(credentials?: Credentials): string | undefined {\n credentials = credentials || this.options.auth;\n if (credentials) {\n const { login, password } = credentials;\n const str = unescape(encodeURIComponent(`${login}:${password}`));\n // @ts-ignore\n if (__BROWSER__) {\n return window.btoa(str);\n } else {\n return Buffer.from(str).toString('base64');\n }\n }\n }\n\n /**\n * Send request to NGW api router.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param params - Request item params or query params\n * @param requestOptions - Request options\n *\n * @example\n * ```javascript\n *\n * // there is such an NGW route item\n * // \"feature_layer.feature.item\": [\n * // \"/api/resource/{0}/feature/{1}\",\n * // \"id\",\n * // \"fid\"\n * // ],\n *\n * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });\n * connector.apiRequest('feature_layer.feature.item', {\n * // request params for {0} and {1}\n * 'id': 2011,\n * 'fid': 101,\n * // query params\n * 'srs': 4326,\n * 'geom_format': 'geojson',\n * }, { method: 'GET' });\n * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'\n *\n * ```\n */\n apiRequest<\n K extends keyof RequestItemsParamsMap,\n P extends RequestItemKeys = RequestItemKeys,\n >(\n name: K,\n params_: RequestItemsParams<K> = {},\n requestOptions: RequestOptions = {},\n ): CancelablePromise<P[K]> {\n const { method, headers, withCredentials, responseType } = requestOptions;\n const params = objectRemoveEmpty(params_);\n const makeApiRequest = () =>\n apiRequest({ name, params, requestOptions, connector: this });\n if (requestOptions.cache && method === 'GET') {\n const cache = new Cache<CancelablePromise<P[K]>>();\n return cache.add(name, makeApiRequest, {\n params,\n ...objectRemoveEmpty({\n headers,\n withCredentials,\n responseType,\n baseUrl: this.options.baseUrl,\n auth: this.options.auth,\n }),\n });\n }\n return makeApiRequest();\n }\n\n /**\n * Shortcut method for send POST request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n *\n * @example\n * ```javascript\n * connector.post('resource.collection', { data: POST_PAYLOAD })\n * .then((newResource) => console.log(newResource))\n * .catch((error) => console.warn(error));\n * ```\n */\n post<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions<'POST'>,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<PostRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'POST';\n return this.apiRequest<K, PostRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send GET request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n get<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions | undefined | null,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<GetRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'GET';\n return this.apiRequest<K, GetRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send PATCH request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n patch<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<PatchRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'PATCH';\n return this.apiRequest<K, PatchRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send PUT request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n put<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<PutRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'PUT';\n return this.apiRequest<K, PutRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Shortcut method for send DELETE request to NGW.\n * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}\n * @param options - Request options\n * @param params - Request item params or query params\n */\n delete<K extends keyof RequestItemsParamsMap>(\n name: K,\n options?: RequestOptions | undefined | null,\n params?: RequestItemsParams<K>,\n ): CancelablePromise<DeleteRequestItemsResponseMap[K]> {\n options = options || {};\n options.method = 'DELETE';\n return this.apiRequest<K, DeleteRequestItemsResponseMap>(\n name,\n params,\n options,\n );\n }\n\n /**\n * Send request to NGW.\n * @param url - URL address to NGW\n * @param params - Query params\n * @param options - Request options\n */\n makeQuery<R = unknown>(\n url: string,\n params?: Params | null,\n options: RequestOptions = {},\n ): CancelablePromise<R> {\n url = (this.options.baseUrl ? this.options.baseUrl : '') + url;\n if (url) {\n if (params) {\n url = template(url, params);\n }\n // remove double slash\n url = fixUrlStr(url);\n return this._loadData(encodeURI(url), options);\n } else {\n throw new Error('Empty `url` not allowed');\n }\n }\n\n // -------------------------------------------------------------------------\n // Resource Methods\n // -------------------------------------------------------------------------\n\n /**\n * {@inheritDoc ResourcesControl.getOne}\n */\n getResource(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getOneOrFail}\n */\n getResourceOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem> {\n return this.resources.getOneOrFail(resource, requestOptions);\n }\n\n /**\n * @deprecated - use {@link NgwConnector.getResource}\n */\n getResourceBy(\n resource: DeepPartial<Resource>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(resource);\n }\n\n /**\n * @deprecated - use {@link NgwConnector.getResource}\n */\n getResourceByKeyname(\n keyname: string,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(keyname);\n }\n\n /**\n * @deprecated - use {@link NgwConnector.getResource}\n */\n getResourceById(id: number): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getOne(id);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getId}\n */\n getResourceId(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number | undefined> {\n return this.resources.getId(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getIdOrFail}\n */\n getResourceIdOrFail(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<number> {\n return this.resources.getIdOrFail(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getMany}\n */\n getResourcesBy(\n resource: DeepPartial<Resource>,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem[]> {\n return this.resources.getMany(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getParent}\n */\n getResourceParent(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.getParent(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.getChildrenOf}\n */\n getResourceChildren(\n resource: ResourceDefinition,\n requestOptions?: Pick<RequestOptions, 'cache'>,\n ): CancelablePromise<ResourceItem[]> {\n return this.resources.getChildrenOf(resource, requestOptions);\n }\n\n /**\n * {@inheritDoc ResourcesControl.update}\n */\n updateResource(\n resource: ResourceIdKeynameDef,\n data: DeepPartial<ResourceItem>,\n ): CancelablePromise<ResourceItem | undefined> {\n return this.resources.update(resource, data);\n }\n\n /**\n * {@inheritDoc ResourcesControl.delete}\n */\n deleteResource(resource: ResourceIdKeynameDef): CancelablePromise<void> {\n return this.resources.delete(resource);\n }\n\n /**\n * @internal\n */\n protected _loadData(\n url: string,\n options: RequestOptions,\n ): CancelablePromise<any> {\n options.responseType = options.responseType || 'json';\n return new CancelablePromise((resolve, reject, onCancel) => {\n if (this.user) {\n options = options || {};\n // options.withCredentials = true;\n options.headers = {\n ...this.getAuthorizationHeaders(),\n ...options.headers,\n };\n }\n loadData(url, resolve, options, reject, onCancel);\n }).catch((httpError) => {\n if (httpError instanceof CancelablePromise.CancelError) {\n // not need to handle cancel error because onCancel method is used\n } else {\n // @ts-ignore\n if (__DEV__) {\n console.warn('DEV WARN', httpError);\n }\n const er = this._handleHttpError(httpError);\n if (er) {\n throw er;\n }\n }\n });\n }\n\n private _handleHttpError(er: Error) {\n if (er) {\n if (er instanceof NgwError) {\n if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {\n throw new ResourceNotFoundError(er);\n } else if (\n er.exception === 'nextgisweb.core.exception.InsufficientPermissions'\n ) {\n throw new InsufficientPermissionsError(er);\n }\n }\n }\n return er;\n }\n}\n","import CancelablePromise from '@nextgis/cancelable-promise';\nimport { template } from './template';\nimport type { NgwConnector } from '../NgwConnector';\nimport type {\n RequestItemKeys,\n RequestItemsParams,\n RequestOptions,\n} from '../interfaces';\nimport type { RequestItemsParamsMap } from '../types/RequestItemsParamsMap';\n\ninterface ApiRequestOptions<K extends keyof RequestItemsParamsMap> {\n name: string;\n connector: NgwConnector;\n params: RequestItemsParams<K>;\n requestOptions: RequestOptions;\n}\n\nexport function apiRequest<\n K extends keyof RequestItemsParamsMap,\n P extends RequestItemKeys = RequestItemKeys,\n>(opt: ApiRequestOptions<K>): CancelablePromise<P[K]> {\n const params = opt.params;\n return new CancelablePromise((resolve, reject) => {\n opt.connector\n .connect()\n .then((apiItems) => {\n let apiItem = apiItems && apiItems[opt.name];\n if (apiItem) {\n apiItem = [...apiItem];\n let url = apiItem.shift();\n if (apiItem.length) {\n const replaceParams: {\n [num: number]: string;\n } = {};\n for (let fry = 0; fry < apiItem.length; fry++) {\n const arg = apiItem[fry];\n replaceParams[fry] = '{' + arg + '}';\n if (params[arg] === undefined) {\n throw new Error(\n '`' + arg + '`' + ' url api argument is not specified',\n );\n }\n }\n if (url) {\n url = template(url, replaceParams);\n }\n }\n // Transfer part of the parameters from `params` to the URL string\n if (params) {\n const paramArray = [];\n const paramList = params.paramList;\n if (Array.isArray(paramList)) {\n delete params.paramList;\n paramList.forEach((x) => {\n paramArray.push(`${x[0]}=${x[1]}`);\n });\n }\n for (const p in params) {\n if (apiItem.indexOf(p) === -1) {\n paramArray.push(`${p}=${params[p]}`);\n }\n }\n if (paramArray.length) {\n url = url + '?' + paramArray.join('&');\n }\n }\n if (url) {\n resolve(opt.connector.makeQuery(url, params, opt.requestOptions));\n } else {\n reject(new Error('request url is not set'));\n }\n } else {\n resolve(undefined);\n }\n })\n .catch((er) => {\n reject(er);\n });\n });\n}\n","/**\n * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API\n *\n * @remarks\n * 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.\n *\n * @packageDocumentation\n * @module ngw-connector\n */\nimport { NgwConnector } from './NgwConnector';\n\nexport * from './interfaces';\nexport * from './types/ResourceItem';\nexport * from './types/FeatureLayer';\nexport * from './types/RequestItemsParamsMap';\nexport * from './types/ResourceStore';\n\n// export { NgwConnector };\nexport default NgwConnector;\n"],"names":["NgwError","Error","constructor","er","super","this","Object","assign","setPrototypeOf","prototype","NetworkError","url","message","location","origin","isObject","val","toString","call","loadData","callback","options","error","onCancel","method","xhr","XMLHttpRequest","open","responseType","getResponseText","JSON","parse","responseText","onload","indexOf","status","forError","cb","response","processingResponse","onerror","upload","onprogress","e","lengthComputable","percentComplete","loaded","total","onProgress","headers","h","header","setRequestHeader","data","undefined","withCredentials","file","FormData","append","d","stringify","abort","send","templateRe","template","str","replace","s","key","value","ResourceNotFoundError","obj","InsufficientPermissionsError","CONNECTORS","addConnector","connector","push","exclude","resourceToQuery","resource","prefix","query","entries","children","parent_id","id","defined","ResourcesControl","Cache","getOne","requestOptions","cache","forCache","opt","keyname","addFull","_fetchResourceBy","_fetchResourceById","CancelablePromise","resolve","getOneOrFail","then","res","getId","getIdOrFail","resp","getMany","_resourceCacheFilter","items","length","get","serialization","resources","x","add","getParent","child","parent","getChildrenOf","i","update","put","delete","_cleanResourceItemCache","all","toDelete","c","cid","includes","catch","matchAll","filter","objectDeepEqual","ID","NgwConnector","EventEmitter","exist","find","baseUrl","auth","findConnector","route","routeStr","create","setNgw","logout","connect","reject","makeQuery","login","password","getUserInfo","credentials","index","splice","removeConnector","user","emitter","emit","clean","getAuthorizationHeaders","client","makeClientId","Authorization","unescape","encodeURIComponent","window","btoa","apiRequest","name","params_","params","objectRemoveEmpty","makeApiRequest","apiItems","apiItem","shift","replaceParams","fry","arg","paramArray","paramList","Array","isArray","forEach","p","join","post","patch","fixUrlStr","_loadData","encodeURI","getResource","getResourceOrFail","getResourceBy","getResourceByKeyname","getResourceById","getResourceId","getResourceIdOrFail","getResourcesBy","getResourceParent","getResourceChildren","updateResource","deleteResource","httpError","CancelError","console","warn","_handleHttpError","exception"],"mappings":"yNAKaA,UAAiBC,MAW5BC,Y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AAcvC,EAAUW,GAMhDgH,eACE3H,EACA1B,GAEA,OAAOhD,KAAK2G,UAAUQ,OAAOzC,EAAU1B,GAMzCsJ,eAAe5H,GACb,OAAO1E,KAAK2G,UAAUU,OAAO3C,GAMrB+G,UACRnL,EACAU,GAGA,OADAA,EAAQO,aAAeP,EAAQO,cAAgB,OACxC,IAAIsE,GAAkB,CAACC,EAASgD,EAAQ5H,KACzClB,KAAKuJ,QACPvI,EAAUA,GAAW,IAEb4B,QAAU,IACb5C,KAAK2J,6BACL3I,EAAQ4B,UAGf9B,EAASR,EAAKwF,EAAS9E,EAAS8H,EAAQ5H,MACvC0G,OAAO2E,IACR,GAAIA,aAAqB1G,EAAkB2G,iBAEpC,sCAGHC,QAAQC,KAAK,WAAYH,GAE3B,MAAMzM,EAAKE,KAAK2M,iBAAiBJ,GACjC,GAAIzM,EACF,MAAMA,MAMN6M,iBAAiB7M,GACvB,GAAIA,GACEA,aAAcH,EAAU,CAC1B,GAAqB,mDAAjBG,EAAG8M,UACL,MAAM,IAAI3I,EAAsBnE,GAC3B,GACY,sDAAjBA,EAAG8M,UAEH,MAAM,IAAIzI,EAA6BrE,GAI7C,OAAOA,GAngBFmI,SAAS,CACdtI,SAAAA,EACAsE,sBAAAA,GE5BJ,MAAegE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Bundle of @nextgis/ngw-connector; version: 1.
|
|
1
|
+
/** Bundle of @nextgis/ngw-connector; version: 1.11.3; author: NextGIS */
|
|
2
2
|
var NgwConnector = (function () {
|
|
3
3
|
'use strict';
|
|
4
4
|
|
|
@@ -82,10 +82,14 @@ var NgwConnector = (function () {
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
function __spreadArray(to, from) {
|
|
86
|
-
for (var i = 0,
|
|
87
|
-
|
|
88
|
-
|
|
85
|
+
function __spreadArray(to, from, pack) {
|
|
86
|
+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
87
|
+
if (ar || !(i in from)) {
|
|
88
|
+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
89
|
+
ar[i] = from[i];
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return to.concat(ar || Array.prototype.slice.call(from));
|
|
89
93
|
}
|
|
90
94
|
|
|
91
95
|
var events = {exports: {}};
|
|
@@ -1032,13 +1036,46 @@ var NgwConnector = (function () {
|
|
|
1032
1036
|
return url.replace(/([^:]\/)\/+/g, '$1');
|
|
1033
1037
|
}
|
|
1034
1038
|
|
|
1039
|
+
/**
|
|
1040
|
+
* @example
|
|
1041
|
+
* ```javascript
|
|
1042
|
+
* const cache1 = new Cache();
|
|
1043
|
+
* cache1.add('foo', 'value');
|
|
1044
|
+
*
|
|
1045
|
+
* const cache2 = new Cache();
|
|
1046
|
+
* cache2.match('foo'); // value
|
|
1047
|
+
*
|
|
1048
|
+
* const cache3 = new Cache({ namespace: 'foo' });
|
|
1049
|
+
* cache3.match('foo'); // undefined
|
|
1050
|
+
* ```
|
|
1051
|
+
*
|
|
1052
|
+
* @example
|
|
1053
|
+
* ```javascript
|
|
1054
|
+
* let COUNTER = 0;
|
|
1055
|
+
* const createPromise = () => new Promise((res) => {
|
|
1056
|
+
* COUNTER++
|
|
1057
|
+
* setTimeout(() => res('Ok'), 300)
|
|
1058
|
+
* });
|
|
1059
|
+
*
|
|
1060
|
+
* const cache = new Cache();
|
|
1061
|
+
* for (let i = 0; i < 10; i++) {
|
|
1062
|
+
* cache.add('foo', createPromise).then((data) => {
|
|
1063
|
+
* console.log(data); // 'Ok'
|
|
1064
|
+
* });
|
|
1065
|
+
* }
|
|
1066
|
+
* console.log(COUNTER); // 1
|
|
1067
|
+
* ```
|
|
1068
|
+
*/
|
|
1035
1069
|
var Cache$1 = /** @class */ (function () {
|
|
1036
|
-
function Cache() {
|
|
1070
|
+
function Cache(options) {
|
|
1071
|
+
if (options === void 0) { options = {}; }
|
|
1072
|
+
var _a;
|
|
1037
1073
|
this.cache = [];
|
|
1038
|
-
|
|
1039
|
-
|
|
1074
|
+
var namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
|
|
1075
|
+
if (Cache.instance[namespace]) {
|
|
1076
|
+
return Cache.instance[namespace];
|
|
1040
1077
|
}
|
|
1041
|
-
Cache.instance = this;
|
|
1078
|
+
Cache.instance[namespace] = this;
|
|
1042
1079
|
return this;
|
|
1043
1080
|
}
|
|
1044
1081
|
Cache.prototype.clean = function () {
|
|
@@ -1047,12 +1084,34 @@ var NgwConnector = (function () {
|
|
|
1047
1084
|
Cache.prototype.all = function () {
|
|
1048
1085
|
return this.cache;
|
|
1049
1086
|
};
|
|
1050
|
-
|
|
1051
|
-
|
|
1087
|
+
/**
|
|
1088
|
+
* Caching only a non-empty value.
|
|
1089
|
+
*
|
|
1090
|
+
* Useful for get or create strategy
|
|
1091
|
+
* @example
|
|
1092
|
+
* ```javascript
|
|
1093
|
+
* const cache = new Cache();
|
|
1094
|
+
* const getItemFunc = () => fetch(url).then((data) => {
|
|
1095
|
+
* return data.json(); // undefined
|
|
1096
|
+
* });
|
|
1097
|
+
* const item = await cache.addFull('foo', getItemFunc);
|
|
1098
|
+
* if (!item) {
|
|
1099
|
+
* await createItem(); // 'New item'
|
|
1100
|
+
* }
|
|
1101
|
+
*
|
|
1102
|
+
* // somewhere else in the code
|
|
1103
|
+
* const item = await cache.addFull('foo', getItemFunc).then((resp) => {
|
|
1104
|
+
* console.log(resp); // 'New item'
|
|
1105
|
+
* })
|
|
1106
|
+
*
|
|
1107
|
+
* ```
|
|
1108
|
+
*/
|
|
1109
|
+
Cache.prototype.addFull = function (key, valueToSet, props) {
|
|
1110
|
+
return this.add(key, valueToSet, props, true);
|
|
1052
1111
|
};
|
|
1053
|
-
Cache.prototype.add = function (key, valueToSet,
|
|
1112
|
+
Cache.prototype.add = function (key, valueToSet, props, onlyFull) {
|
|
1054
1113
|
var _this = this;
|
|
1055
|
-
var exist = this._find(key,
|
|
1114
|
+
var exist = this._find(key, props);
|
|
1056
1115
|
if (!exist) {
|
|
1057
1116
|
var value = void 0;
|
|
1058
1117
|
if (valueToSet instanceof Function) {
|
|
@@ -1061,11 +1120,13 @@ var NgwConnector = (function () {
|
|
|
1061
1120
|
else {
|
|
1062
1121
|
value = valueToSet;
|
|
1063
1122
|
}
|
|
1064
|
-
var
|
|
1123
|
+
var props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
|
|
1065
1124
|
var cacheItem = {
|
|
1066
1125
|
key: key,
|
|
1067
1126
|
value: value,
|
|
1068
|
-
|
|
1127
|
+
props: props_,
|
|
1128
|
+
// TODO: remove backward compatibility use only props
|
|
1129
|
+
options: props_,
|
|
1069
1130
|
};
|
|
1070
1131
|
if (onlyFull && !full(value)) {
|
|
1071
1132
|
return value;
|
|
@@ -1073,13 +1134,13 @@ var NgwConnector = (function () {
|
|
|
1073
1134
|
this.cache.push(cacheItem);
|
|
1074
1135
|
if (value instanceof Promise) {
|
|
1075
1136
|
value.catch(function (er) {
|
|
1076
|
-
_this.delete(key,
|
|
1137
|
+
_this.delete(key, props);
|
|
1077
1138
|
throw er;
|
|
1078
1139
|
});
|
|
1079
1140
|
if (onlyFull) {
|
|
1080
1141
|
value.then(function (x) {
|
|
1081
1142
|
if (!full(x)) {
|
|
1082
|
-
_this.delete(key,
|
|
1143
|
+
_this.delete(key, props);
|
|
1083
1144
|
}
|
|
1084
1145
|
return x;
|
|
1085
1146
|
});
|
|
@@ -1092,26 +1153,26 @@ var NgwConnector = (function () {
|
|
|
1092
1153
|
return exist.value;
|
|
1093
1154
|
}
|
|
1094
1155
|
};
|
|
1095
|
-
Cache.prototype.match = function (key,
|
|
1096
|
-
var cacheRecord = this._find(key,
|
|
1156
|
+
Cache.prototype.match = function (key, props) {
|
|
1157
|
+
var cacheRecord = this._find(key, props);
|
|
1097
1158
|
if (cacheRecord) {
|
|
1098
1159
|
return cacheRecord.value;
|
|
1099
1160
|
}
|
|
1100
1161
|
};
|
|
1101
|
-
Cache.prototype.matchAll = function (key,
|
|
1162
|
+
Cache.prototype.matchAll = function (key, props) {
|
|
1102
1163
|
var _this = this;
|
|
1103
1164
|
if (key) {
|
|
1104
1165
|
return this.cache
|
|
1105
|
-
.filter(function (x) { return _this._filter(x, key,
|
|
1166
|
+
.filter(function (x) { return _this._filter(x, key, props); })
|
|
1106
1167
|
.map(function (x) { return x.value; });
|
|
1107
1168
|
}
|
|
1108
1169
|
return this.cache.map(function (x) { return x.value; });
|
|
1109
1170
|
};
|
|
1110
|
-
Cache.prototype.delete = function (keyOrItem,
|
|
1171
|
+
Cache.prototype.delete = function (keyOrItem, props) {
|
|
1111
1172
|
var _this = this;
|
|
1112
1173
|
var exist = [];
|
|
1113
1174
|
if (typeof keyOrItem === 'string') {
|
|
1114
|
-
exist = this.cache.filter(function (x) { return _this._filter(x, keyOrItem,
|
|
1175
|
+
exist = this.cache.filter(function (x) { return _this._filter(x, keyOrItem, props); });
|
|
1115
1176
|
}
|
|
1116
1177
|
else {
|
|
1117
1178
|
exist.push(keyOrItem);
|
|
@@ -1122,19 +1183,22 @@ var NgwConnector = (function () {
|
|
|
1122
1183
|
this.cache.splice(index, 1);
|
|
1123
1184
|
}
|
|
1124
1185
|
};
|
|
1125
|
-
Cache.prototype._find = function (key,
|
|
1186
|
+
Cache.prototype._find = function (key, props) {
|
|
1126
1187
|
var _this = this;
|
|
1127
|
-
return this.cache.find(function (x) { return _this._filter(x, key,
|
|
1188
|
+
return this.cache.find(function (x) { return _this._filter(x, key, props); });
|
|
1128
1189
|
};
|
|
1129
|
-
Cache.prototype._filter = function (item, key,
|
|
1190
|
+
Cache.prototype._filter = function (item, key, props) {
|
|
1130
1191
|
if (item.key === key) {
|
|
1131
|
-
if (
|
|
1132
|
-
|
|
1192
|
+
if (props) {
|
|
1193
|
+
// TODO: remove backward compatibility
|
|
1194
|
+
var itemProps = item.props || item.options;
|
|
1195
|
+
return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
|
|
1133
1196
|
}
|
|
1134
1197
|
return true;
|
|
1135
1198
|
}
|
|
1136
1199
|
return false;
|
|
1137
1200
|
};
|
|
1201
|
+
Cache.instance = {};
|
|
1138
1202
|
return Cache;
|
|
1139
1203
|
}());
|
|
1140
1204
|
|
|
@@ -1170,12 +1234,16 @@ var NgwConnector = (function () {
|
|
|
1170
1234
|
var _this = _super.call(this) || this;
|
|
1171
1235
|
_this.name = 'NetworkError';
|
|
1172
1236
|
Object.setPrototypeOf(_this, NetworkError.prototype);
|
|
1173
|
-
_this.message = "Unable to request "
|
|
1237
|
+
_this.message = "Unable to request ".concat(url, ".\n Possibly invalid NGW URL entered or CORS not configured to get request from ").concat(location.origin); // /control-panel/cors
|
|
1174
1238
|
return _this;
|
|
1175
1239
|
}
|
|
1176
1240
|
return NetworkError;
|
|
1177
1241
|
}(Error));
|
|
1178
1242
|
|
|
1243
|
+
function isObject(val) {
|
|
1244
|
+
return Object.prototype.toString.call(val) === '[object Object]';
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1179
1247
|
var loadData;
|
|
1180
1248
|
// @ts-ignore
|
|
1181
1249
|
{
|
|
@@ -1211,7 +1279,7 @@ var NgwConnector = (function () {
|
|
|
1211
1279
|
}
|
|
1212
1280
|
};
|
|
1213
1281
|
xhr.onload = function () {
|
|
1214
|
-
if ([401, 403, 404, 500].indexOf(xhr.status) !== -1) {
|
|
1282
|
+
if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
|
|
1215
1283
|
error(new NgwError(getResponseText()));
|
|
1216
1284
|
}
|
|
1217
1285
|
processingResponse();
|
|
@@ -1266,7 +1334,7 @@ var NgwConnector = (function () {
|
|
|
1266
1334
|
data = new FormData();
|
|
1267
1335
|
data.append('file', options.file);
|
|
1268
1336
|
if (options.data) {
|
|
1269
|
-
for (var d in data) {
|
|
1337
|
+
for (var d in options.data) {
|
|
1270
1338
|
data.append(d, data[d]);
|
|
1271
1339
|
}
|
|
1272
1340
|
}
|
|
@@ -1358,10 +1426,6 @@ var NgwConnector = (function () {
|
|
|
1358
1426
|
}
|
|
1359
1427
|
}
|
|
1360
1428
|
|
|
1361
|
-
function isObject(val) {
|
|
1362
|
-
return Object.prototype.toString.call(val) === '[object Object]';
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
1429
|
var exclude = ['description'];
|
|
1366
1430
|
/**
|
|
1367
1431
|
* @remarks
|
|
@@ -1612,7 +1676,7 @@ var NgwConnector = (function () {
|
|
|
1612
1676
|
ResourcesControl.prototype._fetchResourceById = function (id, requestOptions) {
|
|
1613
1677
|
var _this = this;
|
|
1614
1678
|
var promise = function () {
|
|
1615
|
-
return _this.connector.get('resource.item', requestOptions, { id: id })
|
|
1679
|
+
return _this.connector.get('resource.item', requestOptions, { id: id });
|
|
1616
1680
|
};
|
|
1617
1681
|
return this.cache
|
|
1618
1682
|
.add('resource.item', promise, {
|
|
@@ -1659,7 +1723,7 @@ var NgwConnector = (function () {
|
|
|
1659
1723
|
.then(function (apiItems) {
|
|
1660
1724
|
var apiItem = apiItems && apiItems[opt.name];
|
|
1661
1725
|
if (apiItem) {
|
|
1662
|
-
apiItem = __spreadArray([], apiItem);
|
|
1726
|
+
apiItem = __spreadArray([], apiItem, true);
|
|
1663
1727
|
var url = apiItem.shift();
|
|
1664
1728
|
if (apiItem.length) {
|
|
1665
1729
|
var replaceParams = {};
|
|
@@ -1681,12 +1745,12 @@ var NgwConnector = (function () {
|
|
|
1681
1745
|
if (Array.isArray(paramList)) {
|
|
1682
1746
|
delete params.paramList;
|
|
1683
1747
|
paramList.forEach(function (x) {
|
|
1684
|
-
paramArray_1.push(x[0]
|
|
1748
|
+
paramArray_1.push("".concat(x[0], "=").concat(x[1]));
|
|
1685
1749
|
});
|
|
1686
1750
|
}
|
|
1687
1751
|
for (var p in params) {
|
|
1688
1752
|
if (apiItem.indexOf(p) === -1) {
|
|
1689
|
-
paramArray_1.push(p
|
|
1753
|
+
paramArray_1.push("".concat(p, "=").concat(params[p]));
|
|
1690
1754
|
}
|
|
1691
1755
|
}
|
|
1692
1756
|
if (paramArray_1.length) {
|
|
@@ -1820,7 +1884,7 @@ var NgwConnector = (function () {
|
|
|
1820
1884
|
headers: this.getAuthorizationHeaders(credentials),
|
|
1821
1885
|
// withCredentials: true
|
|
1822
1886
|
};
|
|
1823
|
-
// Do not use
|
|
1887
|
+
// Do not use apiRequest('auth.current_user') to avoid circular-references
|
|
1824
1888
|
return this.makeQuery('/api/component/auth/current_user', {}, options)
|
|
1825
1889
|
.then(function (data) {
|
|
1826
1890
|
_this.user = data;
|
|
@@ -1847,7 +1911,7 @@ var NgwConnector = (function () {
|
|
|
1847
1911
|
credentials = credentials || this.options.auth;
|
|
1848
1912
|
if (credentials) {
|
|
1849
1913
|
var login = credentials.login, password = credentials.password;
|
|
1850
|
-
var str = unescape(encodeURIComponent(login
|
|
1914
|
+
var str = unescape(encodeURIComponent("".concat(login, ":").concat(password)));
|
|
1851
1915
|
// @ts-ignore
|
|
1852
1916
|
{
|
|
1853
1917
|
return window.btoa(str);
|