@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.cjs.prod.js","sources":["../src/errors/NgwError.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","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","loadData","url","require","http","https","adapterFor","inputUrl","parse","protocol","callback","options","error","onCancel","Promise","resolve","reject","adapter","requestOpt","headers","method","body","data","JSON","stringify","undefined","Buffer","byteLength","req","request","resp","on","chunk","json","status_code","message","err","write","abort","end","then","catch","templateRe","template","str","replace","s","key","value","ResourceNotFoundError","obj","InsufficientPermissionsError","CONNECTORS","addConnector","connector","push","isObject","val","toString","call","exclude","resourceToQuery","resource","prefix","query","entries","indexOf","children","parent_id","id","defined","ResourcesControl","Cache","getOne","requestOptions","cache","forCache","opt","keyname","addFull","_fetchResourceBy","_fetchResourceById","CancelablePromise","getOneOrFail","res","getId","getIdOrFail","getMany","_resourceCacheFilter","items","length","get","serialization","resources","x","add","getParent","child","parent","getChildrenOf","i","update","put","delete","_cleanResourceItemCache","all","toDelete","c","cid","includes","d","matchAll","filter","objectDeepEqual","ID","NgwConnector","EventEmitter","exist","find","baseUrl","auth","findConnector","route","routeStr","create","setNgw","logout","connect","makeQuery","login","password","getUserInfo","credentials","index","splice","removeConnector","user","emitter","emit","clean","getAuthorizationHeaders","client","makeClientId","Authorization","unescape","encodeURIComponent","from","apiRequest","name","params_","withCredentials","responseType","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","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QACP7H,EAAUA,GAAW,IAEbQ,QAAU,IACbvB,KAAKgJ,6BACLjI,EAAQQ,UAGflB,EAASC,EAAKa,EAASJ,EAASK,EAAQH,MACvC4B,OAAOgJ,IACR,GAAIA,aAAqBvG,EAAkBwG,iBAEpC,CAKL,MAAMhM,EAAKE,KAAK+L,iBAAiBF,GACjC,GAAI/L,EACF,MAAMA,MAMNiM,iBAAiBjM,GACvB,GAAIA,GACEA,aAAcH,EAAU,CAC1B,GAAqB,mDAAjBG,EAAGkM,UACL,MAAM,IAAI3I,EAAsBvD,GAC3B,GACY,sDAAjBA,EAAGkM,UAEH,MAAM,IAAIzI,EAA6BzD,GAI7C,OAAOA,GA/fFyH,SAAS,CACd5H,SAAAA,EACA0D,sBAAAA,kBE5BWkE"}
|
|
1
|
+
{"version":3,"file":"ngw-connector.cjs.prod.js","sources":["../src/errors/NgwError.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","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","isObject","val","toString","call","loadData","url","require","http","https","FormData","adapterFor","inputUrl","parse","protocol","callback","options","error","onCancel","file","headers","method","data","responseType","Promise","resolve","reject","adapter","requestOpt","body","JSON","stringify","form","uploadedFile","fileMeta","file_","name","fileMeta_","filename","append","d","getHeaders","undefined","Buffer","byteLength","req","request","resp","on","chunk","json","status_code","message","pipe","err","write","abort","end","then","catch","templateRe","template","str","replace","s","key","value","ResourceNotFoundError","obj","InsufficientPermissionsError","CONNECTORS","addConnector","connector","push","exclude","resourceToQuery","resource","prefix","query","entries","indexOf","children","parent_id","id","defined","ResourcesControl","Cache","getOne","requestOptions","cache","forCache","opt","keyname","addFull","_fetchResourceBy","_fetchResourceById","CancelablePromise","getOneOrFail","res","getId","getIdOrFail","getMany","_resourceCacheFilter","items","length","get","serialization","resources","x","add","getParent","child","parent","getChildrenOf","i","update","put","delete","_cleanResourceItemCache","all","toDelete","c","cid","includes","matchAll","filter","objectDeepEqual","ID","NgwConnector","EventEmitter","exist","find","baseUrl","auth","findConnector","route","routeStr","create","setNgw","logout","connect","makeQuery","login","password","getUserInfo","credentials","index","splice","removeConnector","user","emitter","emit","clean","getAuthorizationHeaders","client","makeClientId","Authorization","unescape","encodeURIComponent","from","apiRequest","params_","withCredentials","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","_handleHttpError","exception"],"mappings":"oOAKaA,UAAiBC,MAW5BC,YAAYC,GACVC,QAXFC,UAAO,WAYLC,OAAOC,OAAOF,KAAMF,GACpBG,OAAOE,eAAeH,KAAML,EAASS,qBCnBzBC,EAASC,GACvB,MAA+C,oBAAxCL,OAAOG,UAAUG,SAASC,KAAKF,GC+BxC,IAAIG,EAmHG,CACL,MAAMC,EAAMC,QAAQ,OACdC,EAAOD,QAAQ,QACfE,EAAQF,QAAQ,SAChBG,EAAWH,QAAQ,aAEnBI,EAAcC,IACoB,CACpC,QAASJ,EACT,SAAUC,GAEKH,EAAIO,MAAMD,GAAUE,UAAY,WAInDT,EAAW,CACTC,EACAS,EACAC,EAA6C,GAC7CC,EACAC,KAEA,MAAMC,KAAEA,EAAIC,QAAEA,EAAOC,OAAEA,EAAMC,KAAEA,EAAIC,aAAEA,GAAiBP,EA8FtD,OA5FgB,IAAIQ,SAAQ,CAACC,EAASC,KACpC,MAAMC,EAAUhB,EAAWL,GAC3B,IAAIqB,EAuFF,MAAM,IAAInC,MAAM,cAAcc,qBAvFnB,CACX,MAAMsB,EAAa,CACjBR,QAASA,GAAW,GACpBC,OAAAA,GAEIQ,EAAuB,iBAATP,EAAoBA,EAAOQ,KAAKC,UAAUT,GAE9D,IAAIU,EACAC,EAAed,EACnB,GAAIA,EAAM,CACR,MAAMe,EAAW,GACjB,GACEjC,EAASkB,IACT,SAAUA,IACT,aAAcA,GA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A,aAAcH,EAAU,CAC1B,GAAqB,mDAAjBG,EAAG6M,UACL,MAAM,IAAIpI,EAAsBzE,GAC3B,GACY,sDAAjBA,EAAG6M,UAEH,MAAM,IAAIlI,EAA6B3E,GAI7C,OAAOA,GAngBFsI,SAAS,CACdzI,SAAAA,EACA4E,sBAAAA,kBE5BW6D"}
|
|
@@ -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 events = {exports: {}};
|
|
3
3
|
|
|
4
4
|
var R = typeof Reflect === 'object' ? Reflect : null;
|
|
@@ -917,13 +917,45 @@ function fixUrlStr(url) {
|
|
|
917
917
|
return url.replace(/([^:]\/)\/+/g, '$1');
|
|
918
918
|
}
|
|
919
919
|
|
|
920
|
+
/**
|
|
921
|
+
* @example
|
|
922
|
+
* ```javascript
|
|
923
|
+
* const cache1 = new Cache();
|
|
924
|
+
* cache1.add('foo', 'value');
|
|
925
|
+
*
|
|
926
|
+
* const cache2 = new Cache();
|
|
927
|
+
* cache2.match('foo'); // value
|
|
928
|
+
*
|
|
929
|
+
* const cache3 = new Cache({ namespace: 'foo' });
|
|
930
|
+
* cache3.match('foo'); // undefined
|
|
931
|
+
* ```
|
|
932
|
+
*
|
|
933
|
+
* @example
|
|
934
|
+
* ```javascript
|
|
935
|
+
* let COUNTER = 0;
|
|
936
|
+
* const createPromise = () => new Promise((res) => {
|
|
937
|
+
* COUNTER++
|
|
938
|
+
* setTimeout(() => res('Ok'), 300)
|
|
939
|
+
* });
|
|
940
|
+
*
|
|
941
|
+
* const cache = new Cache();
|
|
942
|
+
* for (let i = 0; i < 10; i++) {
|
|
943
|
+
* cache.add('foo', createPromise).then((data) => {
|
|
944
|
+
* console.log(data); // 'Ok'
|
|
945
|
+
* });
|
|
946
|
+
* }
|
|
947
|
+
* console.log(COUNTER); // 1
|
|
948
|
+
* ```
|
|
949
|
+
*/
|
|
920
950
|
class Cache$1 {
|
|
921
|
-
constructor() {
|
|
951
|
+
constructor(options = {}) {
|
|
952
|
+
var _a;
|
|
922
953
|
this.cache = [];
|
|
923
|
-
|
|
924
|
-
|
|
954
|
+
const namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
|
|
955
|
+
if (Cache$1.instance[namespace]) {
|
|
956
|
+
return Cache$1.instance[namespace];
|
|
925
957
|
}
|
|
926
|
-
Cache$1.instance = this;
|
|
958
|
+
Cache$1.instance[namespace] = this;
|
|
927
959
|
return this;
|
|
928
960
|
}
|
|
929
961
|
clean() {
|
|
@@ -932,11 +964,33 @@ class Cache$1 {
|
|
|
932
964
|
all() {
|
|
933
965
|
return this.cache;
|
|
934
966
|
}
|
|
935
|
-
|
|
936
|
-
|
|
967
|
+
/**
|
|
968
|
+
* Caching only a non-empty value.
|
|
969
|
+
*
|
|
970
|
+
* Useful for get or create strategy
|
|
971
|
+
* @example
|
|
972
|
+
* ```javascript
|
|
973
|
+
* const cache = new Cache();
|
|
974
|
+
* const getItemFunc = () => fetch(url).then((data) => {
|
|
975
|
+
* return data.json(); // undefined
|
|
976
|
+
* });
|
|
977
|
+
* const item = await cache.addFull('foo', getItemFunc);
|
|
978
|
+
* if (!item) {
|
|
979
|
+
* await createItem(); // 'New item'
|
|
980
|
+
* }
|
|
981
|
+
*
|
|
982
|
+
* // somewhere else in the code
|
|
983
|
+
* const item = await cache.addFull('foo', getItemFunc).then((resp) => {
|
|
984
|
+
* console.log(resp); // 'New item'
|
|
985
|
+
* })
|
|
986
|
+
*
|
|
987
|
+
* ```
|
|
988
|
+
*/
|
|
989
|
+
addFull(key, valueToSet, props) {
|
|
990
|
+
return this.add(key, valueToSet, props, true);
|
|
937
991
|
}
|
|
938
|
-
add(key, valueToSet,
|
|
939
|
-
const exist = this._find(key,
|
|
992
|
+
add(key, valueToSet, props, onlyFull) {
|
|
993
|
+
const exist = this._find(key, props);
|
|
940
994
|
if (!exist) {
|
|
941
995
|
let value;
|
|
942
996
|
if (valueToSet instanceof Function) {
|
|
@@ -945,11 +999,13 @@ class Cache$1 {
|
|
|
945
999
|
else {
|
|
946
1000
|
value = valueToSet;
|
|
947
1001
|
}
|
|
948
|
-
const
|
|
1002
|
+
const props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
|
|
949
1003
|
const cacheItem = {
|
|
950
1004
|
key,
|
|
951
1005
|
value,
|
|
952
|
-
|
|
1006
|
+
props: props_,
|
|
1007
|
+
// TODO: remove backward compatibility use only props
|
|
1008
|
+
options: props_,
|
|
953
1009
|
};
|
|
954
1010
|
if (onlyFull && !full(value)) {
|
|
955
1011
|
return value;
|
|
@@ -957,13 +1013,13 @@ class Cache$1 {
|
|
|
957
1013
|
this.cache.push(cacheItem);
|
|
958
1014
|
if (value instanceof Promise) {
|
|
959
1015
|
value.catch((er) => {
|
|
960
|
-
this.delete(key,
|
|
1016
|
+
this.delete(key, props);
|
|
961
1017
|
throw er;
|
|
962
1018
|
});
|
|
963
1019
|
if (onlyFull) {
|
|
964
1020
|
value.then((x) => {
|
|
965
1021
|
if (!full(x)) {
|
|
966
|
-
this.delete(key,
|
|
1022
|
+
this.delete(key, props);
|
|
967
1023
|
}
|
|
968
1024
|
return x;
|
|
969
1025
|
});
|
|
@@ -976,24 +1032,24 @@ class Cache$1 {
|
|
|
976
1032
|
return exist.value;
|
|
977
1033
|
}
|
|
978
1034
|
}
|
|
979
|
-
match(key,
|
|
980
|
-
const cacheRecord = this._find(key,
|
|
1035
|
+
match(key, props) {
|
|
1036
|
+
const cacheRecord = this._find(key, props);
|
|
981
1037
|
if (cacheRecord) {
|
|
982
1038
|
return cacheRecord.value;
|
|
983
1039
|
}
|
|
984
1040
|
}
|
|
985
|
-
matchAll(key,
|
|
1041
|
+
matchAll(key, props) {
|
|
986
1042
|
if (key) {
|
|
987
1043
|
return this.cache
|
|
988
|
-
.filter((x) => this._filter(x, key,
|
|
1044
|
+
.filter((x) => this._filter(x, key, props))
|
|
989
1045
|
.map((x) => x.value);
|
|
990
1046
|
}
|
|
991
1047
|
return this.cache.map((x) => x.value);
|
|
992
1048
|
}
|
|
993
|
-
delete(keyOrItem,
|
|
1049
|
+
delete(keyOrItem, props) {
|
|
994
1050
|
let exist = [];
|
|
995
1051
|
if (typeof keyOrItem === 'string') {
|
|
996
|
-
exist = this.cache.filter((x) => this._filter(x, keyOrItem,
|
|
1052
|
+
exist = this.cache.filter((x) => this._filter(x, keyOrItem, props));
|
|
997
1053
|
}
|
|
998
1054
|
else {
|
|
999
1055
|
exist.push(keyOrItem);
|
|
@@ -1003,19 +1059,22 @@ class Cache$1 {
|
|
|
1003
1059
|
this.cache.splice(index, 1);
|
|
1004
1060
|
}
|
|
1005
1061
|
}
|
|
1006
|
-
_find(key,
|
|
1007
|
-
return this.cache.find((x) => this._filter(x, key,
|
|
1062
|
+
_find(key, props) {
|
|
1063
|
+
return this.cache.find((x) => this._filter(x, key, props));
|
|
1008
1064
|
}
|
|
1009
|
-
_filter(item, key,
|
|
1065
|
+
_filter(item, key, props) {
|
|
1010
1066
|
if (item.key === key) {
|
|
1011
|
-
if (
|
|
1012
|
-
|
|
1067
|
+
if (props) {
|
|
1068
|
+
// TODO: remove backward compatibility
|
|
1069
|
+
const itemProps = item.props || item.options;
|
|
1070
|
+
return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
|
|
1013
1071
|
}
|
|
1014
1072
|
return true;
|
|
1015
1073
|
}
|
|
1016
1074
|
return false;
|
|
1017
1075
|
}
|
|
1018
|
-
}
|
|
1076
|
+
}
|
|
1077
|
+
Cache$1.instance = {};
|
|
1019
1078
|
|
|
1020
1079
|
/**
|
|
1021
1080
|
* Caching for asynchronous functions
|
|
@@ -1050,6 +1109,10 @@ class NetworkError extends Error {
|
|
|
1050
1109
|
}
|
|
1051
1110
|
}
|
|
1052
1111
|
|
|
1112
|
+
function isObject(val) {
|
|
1113
|
+
return Object.prototype.toString.call(val) === '[object Object]';
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1053
1116
|
let loadData;
|
|
1054
1117
|
// @ts-ignore
|
|
1055
1118
|
{
|
|
@@ -1083,7 +1146,7 @@ let loadData;
|
|
|
1083
1146
|
}
|
|
1084
1147
|
};
|
|
1085
1148
|
xhr.onload = () => {
|
|
1086
|
-
if ([401, 403, 404, 500].indexOf(xhr.status) !== -1) {
|
|
1149
|
+
if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
|
|
1087
1150
|
error(new NgwError(getResponseText()));
|
|
1088
1151
|
}
|
|
1089
1152
|
processingResponse();
|
|
@@ -1138,7 +1201,7 @@ let loadData;
|
|
|
1138
1201
|
data = new FormData();
|
|
1139
1202
|
data.append('file', options.file);
|
|
1140
1203
|
if (options.data) {
|
|
1141
|
-
for (const d in data) {
|
|
1204
|
+
for (const d in options.data) {
|
|
1142
1205
|
data.append(d, data[d]);
|
|
1143
1206
|
}
|
|
1144
1207
|
}
|
|
@@ -1224,10 +1287,6 @@ function removeConnector(connector) {
|
|
|
1224
1287
|
}
|
|
1225
1288
|
}
|
|
1226
1289
|
|
|
1227
|
-
function isObject(val) {
|
|
1228
|
-
return Object.prototype.toString.call(val) === '[object Object]';
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
1290
|
const exclude = ['description'];
|
|
1232
1291
|
/**
|
|
1233
1292
|
* @remarks
|
|
@@ -1452,7 +1511,7 @@ class ResourcesControl {
|
|
|
1452
1511
|
}
|
|
1453
1512
|
}
|
|
1454
1513
|
_fetchResourceById(id, requestOptions) {
|
|
1455
|
-
const promise = () => this.connector.get('resource.item', requestOptions, { id })
|
|
1514
|
+
const promise = () => this.connector.get('resource.item', requestOptions, { id });
|
|
1456
1515
|
return this.cache
|
|
1457
1516
|
.add('resource.item', promise, {
|
|
1458
1517
|
id,
|
|
@@ -1654,7 +1713,7 @@ class NgwConnector$1 {
|
|
|
1654
1713
|
headers: this.getAuthorizationHeaders(credentials),
|
|
1655
1714
|
// withCredentials: true
|
|
1656
1715
|
};
|
|
1657
|
-
// Do not use
|
|
1716
|
+
// Do not use apiRequest('auth.current_user') to avoid circular-references
|
|
1658
1717
|
return this.makeQuery('/api/component/auth/current_user', {}, options)
|
|
1659
1718
|
.then((data) => {
|
|
1660
1719
|
this.user = data;
|