@carto/api-client 0.3.1 → 0.4.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/build/api/carto-api-error.d.ts +26 -0
  2. package/build/api/endpoints.d.ts +24 -0
  3. package/build/api/index.d.ts +5 -0
  4. package/build/api/query.d.ts +3 -0
  5. package/build/api/request-with-parameters.d.ts +8 -0
  6. package/build/api-client.cjs +724 -65
  7. package/build/api-client.cjs.map +1 -1
  8. package/build/api-client.modern.js +607 -59
  9. package/build/api-client.modern.js.map +1 -1
  10. package/build/constants-internal.d.ts +9 -28
  11. package/build/constants.d.ts +24 -2
  12. package/build/index.d.ts +5 -1
  13. package/build/models/model.d.ts +2 -2
  14. package/build/sources/base-source.d.ts +4 -0
  15. package/build/sources/boundary-query-source.d.ts +9 -0
  16. package/build/sources/boundary-table-source.d.ts +7 -0
  17. package/build/sources/h3-query-source.d.ts +3 -0
  18. package/build/sources/h3-table-source.d.ts +3 -0
  19. package/build/sources/h3-tileset-source.d.ts +3 -0
  20. package/build/sources/index.d.ts +27 -5
  21. package/build/sources/quadbin-query-source.d.ts +3 -0
  22. package/build/sources/quadbin-table-source.d.ts +3 -0
  23. package/build/sources/quadbin-tileset-source.d.ts +3 -0
  24. package/build/sources/raster-source.d.ts +3 -0
  25. package/build/sources/types.d.ts +209 -85
  26. package/build/sources/vector-query-source.d.ts +3 -0
  27. package/build/sources/vector-table-source.d.ts +3 -0
  28. package/build/sources/vector-tileset-source.d.ts +3 -0
  29. package/build/types-internal.d.ts +46 -1
  30. package/build/types.d.ts +11 -0
  31. package/build/utils.d.ts +4 -0
  32. package/build/widget-sources/index.d.ts +5 -0
  33. package/build/widget-sources/types.d.ts +95 -0
  34. package/build/{sources → widget-sources}/widget-base-source.d.ts +2 -2
  35. package/build/{sources → widget-sources}/widget-query-source.d.ts +1 -1
  36. package/build/{sources → widget-sources}/widget-table-source.d.ts +1 -1
  37. package/build/{sources → widget-sources}/wrappers.d.ts +1 -1
  38. package/package.json +4 -3
  39. package/src/api/carto-api-error.ts +88 -0
  40. package/src/api/endpoints.ts +84 -0
  41. package/src/api/index.ts +14 -0
  42. package/src/api/query.ts +56 -0
  43. package/src/api/request-with-parameters.ts +135 -0
  44. package/src/constants-internal.ts +9 -30
  45. package/src/constants.ts +32 -3
  46. package/src/global.d.ts +3 -0
  47. package/src/index.ts +38 -1
  48. package/src/models/model.ts +4 -6
  49. package/src/sources/base-source.ts +101 -0
  50. package/src/sources/boundary-query-source.ts +53 -0
  51. package/src/sources/boundary-table-source.ts +41 -0
  52. package/src/sources/h3-query-source.ts +63 -0
  53. package/src/sources/h3-table-source.ts +59 -0
  54. package/src/sources/h3-tileset-source.ts +26 -0
  55. package/src/sources/index.ts +54 -5
  56. package/src/sources/quadbin-query-source.ts +64 -0
  57. package/src/sources/quadbin-table-source.ts +60 -0
  58. package/src/sources/quadbin-tileset-source.ts +26 -0
  59. package/src/sources/raster-source.ts +34 -0
  60. package/src/sources/types.ts +221 -89
  61. package/src/sources/vector-query-source.ts +65 -0
  62. package/src/sources/vector-table-source.ts +59 -0
  63. package/src/sources/vector-tileset-source.ts +26 -0
  64. package/src/types-internal.ts +54 -1
  65. package/src/types.ts +16 -0
  66. package/src/utils.ts +8 -0
  67. package/src/widget-sources/index.ts +5 -0
  68. package/src/widget-sources/types.ts +105 -0
  69. package/src/{sources → widget-sources}/widget-base-source.ts +5 -5
  70. package/src/{sources → widget-sources}/widget-query-source.ts +2 -3
  71. package/src/{sources → widget-sources}/widget-table-source.ts +2 -3
  72. package/src/{sources → widget-sources}/wrappers.ts +1 -22
@@ -0,0 +1,88 @@
1
+ // deck.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {MapType} from '../types';
6
+
7
+ export type APIRequestType =
8
+ | 'Map data'
9
+ | 'Map instantiation'
10
+ | 'Public map'
11
+ | 'Tile stats'
12
+ | 'SQL'
13
+ | 'Basemap style';
14
+
15
+ export type APIErrorContext = {
16
+ requestType: APIRequestType;
17
+ mapId?: string;
18
+ connection?: string;
19
+ source?: string;
20
+ type?: MapType;
21
+ };
22
+
23
+ /**
24
+ *
25
+ * Custom error for reported errors in CARTO Maps API.
26
+ * Provides useful debugging information in console and context for applications.
27
+ *
28
+ */
29
+ export class CartoAPIError extends Error {
30
+ /** Source error from server */
31
+ error: Error;
32
+
33
+ /** Context (API call & parameters) in which error occured */
34
+ errorContext: APIErrorContext;
35
+
36
+ /** Response from server */
37
+ response?: Response;
38
+
39
+ /** JSON Response from server */
40
+ responseJson?: any;
41
+
42
+ constructor(
43
+ error: Error,
44
+ errorContext: APIErrorContext,
45
+ response?: Response,
46
+ responseJson?: any
47
+ ) {
48
+ let responseString = 'Failed to connect';
49
+ if (response) {
50
+ responseString = 'Server returned: ';
51
+ if (response.status === 400) {
52
+ responseString += 'Bad request';
53
+ } else if (response.status === 401 || response.status === 403) {
54
+ responseString += 'Unauthorized access';
55
+ } else if (response.status === 404) {
56
+ responseString += 'Not found';
57
+ } else {
58
+ responseString += 'Error';
59
+ }
60
+
61
+ responseString += ` (${response.status}):`;
62
+ }
63
+ responseString += ` ${error.message || error}`;
64
+
65
+ let message = `${errorContext.requestType} API request failed`;
66
+ message += `\n${responseString}`;
67
+ for (const key of Object.keys(errorContext)) {
68
+ if (key === 'requestType') continue;
69
+ message += `\n${formatErrorKey(key)}: ${(errorContext as any)[key]}`;
70
+ }
71
+ message += '\n';
72
+
73
+ super(message);
74
+
75
+ this.name = 'CartoAPIError';
76
+ this.response = response;
77
+ this.responseJson = responseJson;
78
+ this.error = error;
79
+ this.errorContext = errorContext;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Converts camelCase to Camel Case
85
+ */
86
+ function formatErrorKey(key: string) {
87
+ return key.replace(/([A-Z])/g, ' $1').replace(/^./, (s) => s.toUpperCase());
88
+ }
@@ -0,0 +1,84 @@
1
+ // deck.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {MapType} from '../types.js';
6
+
7
+ export type V3Endpoint = 'maps' | 'stats' | 'sql';
8
+
9
+ function joinPath(...args: string[]): string {
10
+ return args
11
+ .map((part) => (part.endsWith('/') ? part.slice(0, -1) : part))
12
+ .join('/');
13
+ }
14
+
15
+ function buildV3Path(
16
+ apiBaseUrl: string,
17
+ version: 'v3',
18
+ endpoint: V3Endpoint,
19
+ ...rest: string[]
20
+ ): string {
21
+ return joinPath(apiBaseUrl, version, endpoint, ...rest);
22
+ }
23
+
24
+ /** @internal Required by fetchMap(). */
25
+ export function buildPublicMapUrl({
26
+ apiBaseUrl,
27
+ cartoMapId,
28
+ }: {
29
+ apiBaseUrl: string;
30
+ cartoMapId: string;
31
+ }): string {
32
+ return buildV3Path(apiBaseUrl, 'v3', 'maps', 'public', cartoMapId);
33
+ }
34
+
35
+ /** @internal Required by fetchMap(). */
36
+ export function buildStatsUrl({
37
+ attribute,
38
+ apiBaseUrl,
39
+ connectionName,
40
+ source,
41
+ type,
42
+ }: {
43
+ attribute: string;
44
+ apiBaseUrl: string;
45
+ connectionName: string;
46
+ source: string;
47
+ type: MapType;
48
+ }): string {
49
+ if (type === 'query') {
50
+ return buildV3Path(apiBaseUrl, 'v3', 'stats', connectionName, attribute);
51
+ }
52
+
53
+ // type === 'table'
54
+ return buildV3Path(
55
+ apiBaseUrl,
56
+ 'v3',
57
+ 'stats',
58
+ connectionName,
59
+ source,
60
+ attribute
61
+ );
62
+ }
63
+
64
+ export function buildSourceUrl({
65
+ apiBaseUrl,
66
+ connectionName,
67
+ endpoint,
68
+ }: {
69
+ apiBaseUrl: string;
70
+ connectionName: string;
71
+ endpoint: MapType;
72
+ }): string {
73
+ return buildV3Path(apiBaseUrl, 'v3', 'maps', connectionName, endpoint);
74
+ }
75
+
76
+ export function buildQueryUrl({
77
+ apiBaseUrl,
78
+ connectionName,
79
+ }: {
80
+ apiBaseUrl: string;
81
+ connectionName: string;
82
+ }): string {
83
+ return buildV3Path(apiBaseUrl, 'v3', 'sql', connectionName, 'query');
84
+ }
@@ -0,0 +1,14 @@
1
+ // deck.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ export {
6
+ CartoAPIError,
7
+ APIErrorContext,
8
+ APIRequestType,
9
+ } from './carto-api-error.js';
10
+ // Internal, but required for fetchMap().
11
+ export {buildPublicMapUrl, buildStatsUrl} from './endpoints.js';
12
+ export {query} from './query.js';
13
+ export type {QueryOptions} from './query.js';
14
+ export {requestWithParameters} from './request-with-parameters.js';
@@ -0,0 +1,56 @@
1
+ // deck.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {SOURCE_DEFAULTS} from '../sources/index';
6
+ import type {
7
+ SourceOptions,
8
+ QuerySourceOptions,
9
+ QueryResult,
10
+ } from '../sources/types';
11
+ import {buildQueryUrl} from './endpoints';
12
+ import {requestWithParameters} from './request-with-parameters';
13
+ import {APIErrorContext} from './carto-api-error';
14
+
15
+ export type QueryOptions = SourceOptions &
16
+ Omit<QuerySourceOptions, 'spatialDataColumn'>;
17
+ type UrlParameters = {q: string; queryParameters?: string};
18
+
19
+ export const query = async function (
20
+ options: QueryOptions
21
+ ): Promise<QueryResult> {
22
+ const {
23
+ apiBaseUrl = SOURCE_DEFAULTS.apiBaseUrl,
24
+ clientId = SOURCE_DEFAULTS.clientId,
25
+ maxLengthURL = SOURCE_DEFAULTS.maxLengthURL,
26
+ connectionName,
27
+ sqlQuery,
28
+ queryParameters,
29
+ } = options;
30
+ const urlParameters: UrlParameters = {q: sqlQuery};
31
+
32
+ if (queryParameters) {
33
+ urlParameters.queryParameters = JSON.stringify(queryParameters);
34
+ }
35
+
36
+ const baseUrl = buildQueryUrl({apiBaseUrl, connectionName});
37
+ const headers = {
38
+ Authorization: `Bearer ${options.accessToken}`,
39
+ ...options.headers,
40
+ };
41
+ const parameters = {client: clientId, ...urlParameters};
42
+
43
+ const errorContext: APIErrorContext = {
44
+ requestType: 'SQL',
45
+ connection: options.connectionName,
46
+ type: 'query',
47
+ source: JSON.stringify(parameters, undefined, 2),
48
+ };
49
+ return await requestWithParameters<QueryResult>({
50
+ baseUrl,
51
+ parameters,
52
+ headers,
53
+ errorContext,
54
+ maxLengthURL,
55
+ });
56
+ };
@@ -0,0 +1,135 @@
1
+ // deck.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {isPureObject} from '../utils';
6
+ import {CartoAPIError, APIErrorContext} from './carto-api-error';
7
+ import {V3_MINOR_VERSION} from '../constants-internal';
8
+ import {DEFAULT_CLIENT, DEFAULT_MAX_LENGTH_URL} from '../constants';
9
+
10
+ const DEFAULT_HEADERS = {
11
+ Accept: 'application/json',
12
+ 'Content-Type': 'application/json',
13
+ };
14
+
15
+ const REQUEST_CACHE = new Map<string, Promise<unknown>>();
16
+
17
+ export async function requestWithParameters<T = any>({
18
+ baseUrl,
19
+ parameters = {},
20
+ headers: customHeaders = {},
21
+ errorContext,
22
+ maxLengthURL = DEFAULT_MAX_LENGTH_URL,
23
+ }: {
24
+ baseUrl: string;
25
+ parameters?: Record<string, unknown>;
26
+ headers?: Record<string, string>;
27
+ errorContext: APIErrorContext;
28
+ maxLengthURL?: number;
29
+ }): Promise<T> {
30
+ // Parameters added to all requests issued with `requestWithParameters()`.
31
+ // These parameters override parameters already in the base URL, but not
32
+ // user-provided parameters.
33
+ parameters = {
34
+ v: V3_MINOR_VERSION,
35
+ clientId: DEFAULT_CLIENT,
36
+ ...(typeof deck !== 'undefined' &&
37
+ deck.VERSION && {deckglVersion: deck.VERSION}),
38
+ ...parameters,
39
+ };
40
+
41
+ baseUrl = excludeURLParameters(baseUrl, Object.keys(parameters));
42
+ const key = createCacheKey(baseUrl, parameters, customHeaders);
43
+ if (REQUEST_CACHE.has(key)) {
44
+ return REQUEST_CACHE.get(key) as Promise<T>;
45
+ }
46
+
47
+ const url = createURLWithParameters(baseUrl, parameters);
48
+ const headers = {...DEFAULT_HEADERS, ...customHeaders};
49
+
50
+ /* global fetch */
51
+ const fetchPromise =
52
+ url.length > maxLengthURL
53
+ ? fetch(baseUrl, {
54
+ method: 'POST',
55
+ body: JSON.stringify(parameters),
56
+ headers,
57
+ })
58
+ : fetch(url, {headers});
59
+
60
+ let response: Response | undefined;
61
+ let responseJson: unknown;
62
+ const jsonPromise: Promise<T> = fetchPromise
63
+ .then((_response: Response) => {
64
+ response = _response;
65
+ return response.json();
66
+ })
67
+ .then((json: any) => {
68
+ responseJson = json;
69
+ if (!response || !response.ok) {
70
+ throw new Error(json.error);
71
+ }
72
+ return json;
73
+ })
74
+ .catch((error: Error) => {
75
+ REQUEST_CACHE.delete(key);
76
+ throw new CartoAPIError(error, errorContext, response, responseJson);
77
+ });
78
+
79
+ REQUEST_CACHE.set(key, jsonPromise);
80
+ return jsonPromise;
81
+ }
82
+
83
+ function createCacheKey(
84
+ baseUrl: string,
85
+ parameters: Record<string, unknown>,
86
+ headers: Record<string, string>
87
+ ): string {
88
+ const parameterEntries = Object.entries(parameters).sort(([a], [b]) =>
89
+ a > b ? 1 : -1
90
+ );
91
+ const headerEntries = Object.entries(headers).sort(([a], [b]) =>
92
+ a > b ? 1 : -1
93
+ );
94
+ return JSON.stringify({
95
+ baseUrl,
96
+ parameters: parameterEntries,
97
+ headers: headerEntries,
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Appends query string parameters to a URL. Existing URL parameters are kept,
103
+ * unless there is a conflict, in which case the new parameters override
104
+ * those already in the URL.
105
+ */
106
+ function createURLWithParameters(
107
+ baseUrlString: string,
108
+ parameters: Record<string, unknown>
109
+ ): string {
110
+ const baseUrl = new URL(baseUrlString);
111
+ for (const [key, value] of Object.entries(parameters)) {
112
+ if (isPureObject(value) || Array.isArray(value)) {
113
+ baseUrl.searchParams.set(key, JSON.stringify(value));
114
+ } else {
115
+ baseUrl.searchParams.set(
116
+ key,
117
+ (value as string | boolean | number).toString()
118
+ );
119
+ }
120
+ }
121
+ return baseUrl.toString();
122
+ }
123
+
124
+ /**
125
+ * Deletes query string parameters from a URL.
126
+ */
127
+ function excludeURLParameters(baseUrlString: string, parameters: string[]) {
128
+ const baseUrl = new URL(baseUrlString);
129
+ for (const param of parameters) {
130
+ if (baseUrl.searchParams.has(param)) {
131
+ baseUrl.searchParams.delete(param);
132
+ }
133
+ }
134
+ return baseUrl.toString();
135
+ }
@@ -1,45 +1,24 @@
1
1
  /******************************************************************************
2
- * DEFAULTS
2
+ * VERSIONS
3
3
  */
4
4
 
5
5
  /**
6
- * @internalRemarks Source: @carto/constants
6
+ * Current version of @carto/api-client.
7
7
  * @internal
8
8
  */
9
- export const DEFAULT_API_BASE_URL = 'https://gcp-us-east1.api.carto.com';
9
+ export const API_CLIENT_VERSION = __CARTO_API_CLIENT_VERSION;
10
10
 
11
- /**
12
- * @internalRemarks Source: @carto/constants
13
- * @internal
14
- */
15
- export const DEFAULT_CLIENT = 'deck-gl-carto';
16
-
17
- /**
18
- * @internalRemarks Source: @carto/react-api
19
- * @internal
20
- */
21
- export const DEFAULT_GEO_COLUMN = 'geom';
22
-
23
- /******************************************************************************
24
- * ENUMS
25
- */
11
+ /** @internal */
12
+ export const V3_MINOR_VERSION = '3.4';
26
13
 
27
14
  /**
15
+ * @internalRemarks Source: @deck.gl/carto
28
16
  * @internal
29
- * @internalRemarks Source: @carto/constants
30
17
  */
31
- export enum MapType {
32
- TABLE = 'table',
33
- QUERY = 'query',
34
- TILESET = 'tileset',
35
- }
18
+ export const DEFAULT_AGGREGATION_RES_LEVEL_H3 = 4;
36
19
 
37
20
  /**
21
+ * @internalRemarks Source: @deck.gl/carto
38
22
  * @internal
39
- * @internalRemarks Source: @carto/constants
40
23
  */
41
- export enum ApiVersion {
42
- V1 = 'v1',
43
- V2 = 'v2',
44
- V3 = 'v3',
45
- }
24
+ export const DEFAULT_AGGREGATION_RES_LEVEL_QUADBIN = 6;
package/src/constants.ts CHANGED
@@ -1,6 +1,3 @@
1
- /** Current version of @carto/api-client. */
2
- export const API_CLIENT_VERSION = __CARTO_API_CLIENT_VERSION;
3
-
4
1
  /**
5
2
  * Defines a comparator used when matching a column's values against given filter values.
6
3
  *
@@ -24,3 +21,35 @@ export enum FilterType {
24
21
  TIME = 'time',
25
22
  STRING_SEARCH = 'stringSearch',
26
23
  }
24
+
25
+ /** @internalRemarks Source: @carto/constants */
26
+ export enum ApiVersion {
27
+ V1 = 'v1',
28
+ V2 = 'v2',
29
+ V3 = 'v3',
30
+ }
31
+
32
+ /******************************************************************************
33
+ * DEFAULTS
34
+ */
35
+
36
+ /** @internalRemarks Source: @carto/constants, @deck.gl/carto */
37
+ export const DEFAULT_API_BASE_URL = 'https://gcp-us-east1.api.carto.com';
38
+
39
+ /** @internalRemarks Source: @carto/constants, @deck.gl/carto */
40
+ export const DEFAULT_CLIENT = 'deck-gl-carto';
41
+
42
+ /** @internalRemarks Source: @carto/constants, @deck.gl/carto */
43
+ export const DEFAULT_GEO_COLUMN = 'geom';
44
+
45
+ /**
46
+ * Fastly default limit is 8192; leave some padding.
47
+ * @internalRemarks Source: @deck.gl/carto
48
+ */
49
+ export const DEFAULT_MAX_LENGTH_URL = 7000;
50
+
51
+ /** @internalRemarks Source: @deck.gl/carto */
52
+ export const DEFAULT_TILE_SIZE = 512;
53
+
54
+ /** @internalRemarks Source: @deck.gl/carto */
55
+ export const DEFAULT_TILE_RESOLUTION = 0.5;
package/src/global.d.ts CHANGED
@@ -5,3 +5,6 @@
5
5
  * ```
6
6
  */
7
7
  declare const __CARTO_API_CLIENT_VERSION: string;
8
+
9
+ /** Defined by @deck.gl/core. */
10
+ declare const deck: {VERSION: string | undefined} | undefined;
package/src/index.ts CHANGED
@@ -2,5 +2,42 @@ export * from './client.js';
2
2
  export * from './constants.js';
3
3
  export * from './filters.js';
4
4
  export * from './geo.js';
5
- export * from './sources/index.js';
5
+ export * from './widget-sources/index.js';
6
6
  export * from './types.js';
7
+
8
+ export {
9
+ APIErrorContext,
10
+ APIRequestType,
11
+ CartoAPIError,
12
+ QueryOptions,
13
+ buildPublicMapUrl, // Internal, but required for fetchMap().
14
+ buildStatsUrl, // Internal, but required for fetchMap().
15
+ query,
16
+ requestWithParameters,
17
+ } from './api/index.js';
18
+
19
+ export {
20
+ GeojsonResult,
21
+ JsonResult,
22
+ QueryResult,
23
+ QuerySourceOptions,
24
+ SOURCE_DEFAULTS,
25
+ SourceOptions,
26
+ TableSourceOptions,
27
+ TilejsonResult,
28
+ TilesetSourceOptions,
29
+
30
+ // Sources not wrapped in './widget-sources/index.js';
31
+ BoundaryQuerySourceOptions,
32
+ BoundaryTableSourceOptions,
33
+ H3TilesetSourceOptions,
34
+ QuadbinTilesetSourceOptions,
35
+ RasterSourceOptions,
36
+ VectorTilesetSourceOptions,
37
+ boundaryQuerySource,
38
+ boundaryTableSource,
39
+ h3TilesetSource,
40
+ quadbinTilesetSource,
41
+ rasterSource,
42
+ vectorTilesetSource,
43
+ } from './sources/index.js';
@@ -1,17 +1,15 @@
1
- import {
2
- ApiVersion,
3
- DEFAULT_GEO_COLUMN,
4
- MapType,
5
- } from '../constants-internal.js';
1
+ import {DEFAULT_GEO_COLUMN} from '../constants.js';
6
2
  import {
7
3
  Filter,
8
4
  FilterLogicalOperator,
5
+ MapType,
9
6
  QueryParameters,
10
7
  SpatialFilter,
11
8
  } from '../types.js';
12
9
  import {$TODO} from '../types-internal.js';
13
10
  import {assert} from '../utils.js';
14
11
  import {ModelRequestOptions, makeCall} from './common.js';
12
+ import {ApiVersion} from '../constants.js';
15
13
 
16
14
  /** @internalRemarks Source: @carto/react-api */
17
15
  const AVAILABLE_MODELS = [
@@ -72,7 +70,7 @@ export function executeModel(props: {
72
70
  assert(apiBaseUrl, 'executeModel: missing apiBaseUrl');
73
71
  assert(accessToken, 'executeModel: missing accessToken');
74
72
  assert(apiVersion === V3, 'executeModel: SQL Model API requires CARTO 3+');
75
- assert(type !== MapType.TILESET, 'executeModel: Tilesets not supported');
73
+ assert(type !== 'tileset', 'executeModel: Tilesets not supported');
76
74
 
77
75
  let url = `${apiBaseUrl}/v3/sql/${connectionName}/model/${model}`;
78
76
 
@@ -0,0 +1,101 @@
1
+ // deck.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ /* eslint-disable camelcase */
6
+ import {
7
+ DEFAULT_API_BASE_URL,
8
+ DEFAULT_CLIENT,
9
+ DEFAULT_MAX_LENGTH_URL,
10
+ } from '../constants';
11
+ import {buildSourceUrl} from '../api/endpoints';
12
+ import {requestWithParameters} from '../api/request-with-parameters';
13
+ import type {
14
+ GeojsonResult,
15
+ JsonResult,
16
+ SourceOptionalOptions,
17
+ SourceRequiredOptions,
18
+ TilejsonMapInstantiation,
19
+ TilejsonResult,
20
+ } from './types';
21
+ import {MapType} from '../types';
22
+ import {APIErrorContext} from '../api';
23
+
24
+ export const SOURCE_DEFAULTS: SourceOptionalOptions = {
25
+ apiBaseUrl: DEFAULT_API_BASE_URL,
26
+ clientId: DEFAULT_CLIENT,
27
+ format: 'tilejson',
28
+ headers: {},
29
+ maxLengthURL: DEFAULT_MAX_LENGTH_URL,
30
+ };
31
+
32
+ export async function baseSource<UrlParameters extends Record<string, unknown>>(
33
+ endpoint: MapType,
34
+ options: Partial<SourceOptionalOptions> & SourceRequiredOptions,
35
+ urlParameters: UrlParameters
36
+ ): Promise<TilejsonResult | GeojsonResult | JsonResult> {
37
+ const {accessToken, connectionName, cache, ...optionalOptions} = options;
38
+ const mergedOptions = {
39
+ ...SOURCE_DEFAULTS,
40
+ accessToken,
41
+ connectionName,
42
+ endpoint,
43
+ };
44
+ for (const key in optionalOptions) {
45
+ if (optionalOptions[key as keyof typeof optionalOptions]) {
46
+ (mergedOptions as any)[key] =
47
+ optionalOptions[key as keyof typeof optionalOptions];
48
+ }
49
+ }
50
+ const baseUrl = buildSourceUrl(mergedOptions);
51
+ const {clientId, maxLengthURL, format} = mergedOptions;
52
+ const headers = {
53
+ Authorization: `Bearer ${options.accessToken}`,
54
+ ...options.headers,
55
+ };
56
+ const parameters = {client: clientId, ...urlParameters};
57
+
58
+ const errorContext: APIErrorContext = {
59
+ requestType: 'Map instantiation',
60
+ connection: options.connectionName,
61
+ type: endpoint,
62
+ source: JSON.stringify(parameters, undefined, 2),
63
+ };
64
+ const mapInstantiation =
65
+ await requestWithParameters<TilejsonMapInstantiation>({
66
+ baseUrl,
67
+ parameters,
68
+ headers,
69
+ errorContext,
70
+ maxLengthURL,
71
+ });
72
+
73
+ const dataUrl = mapInstantiation[format].url[0];
74
+ if (cache) {
75
+ cache.value = parseInt(
76
+ new URL(dataUrl).searchParams.get('cache') || '',
77
+ 10
78
+ );
79
+ }
80
+ errorContext.requestType = 'Map data';
81
+
82
+ if (format === 'tilejson') {
83
+ const json = await requestWithParameters<TilejsonResult>({
84
+ baseUrl: dataUrl,
85
+ headers,
86
+ errorContext,
87
+ maxLengthURL,
88
+ });
89
+ if (accessToken) {
90
+ json.accessToken = accessToken;
91
+ }
92
+ return json;
93
+ }
94
+
95
+ return await requestWithParameters<GeojsonResult | JsonResult>({
96
+ baseUrl: dataUrl,
97
+ headers,
98
+ errorContext,
99
+ maxLengthURL,
100
+ });
101
+ }