Skip to content

Commit 730bbfc

Browse files
stepankuzmingithub-actions[bot]
authored andcommitted
Add docs for RequestTransformFunction
GitOrigin-RevId: b9963ac36ff160574670f9ab3a21318ec74ce596
1 parent 8800922 commit 730bbfc

7 files changed

Lines changed: 81 additions & 38 deletions

File tree

src/index.esm.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ export type {Event, ErrorEvent} from './util/evented';
1919
export type {GeoJSONFeature, TargetFeature} from './util/vectortile_to_geojson';
2020
export type {InteractionEvent} from './ui/interactions';
2121
export type {PaddingOptions} from './geo/edge_insets';
22-
export type {RequestParameters} from './util/ajax';
23-
export type {RequestTransformFunction, ResourceType} from './util/mapbox';
22+
export type {RequestParameters, RequestTransformFunction, ResourceType} from './util/ajax';
2423
export type {LngLatLike, LngLatBoundsLike} from './geo/lng_lat';
2524

2625
export type {FeatureSelector} from './style/style';

src/index.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,7 @@ export type {Event, ErrorEvent} from './util/evented';
4848
export type {GeoJSONFeature, TargetFeature} from './util/vectortile_to_geojson';
4949
export type {InteractionEvent} from './ui/interactions';
5050
export type {PaddingOptions} from './geo/edge_insets';
51-
export type {RequestParameters} from './util/ajax';
52-
export type {RequestTransformFunction, ResourceType} from './util/mapbox';
51+
export type {RequestParameters, RequestTransformFunction, ResourceType} from './util/ajax';
5352
export type {LngLatLike, LngLatBoundsLike} from './geo/lng_lat';
5453

5554
export type {FeatureSelector} from './style/style';

src/types/deprecated-aliases.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type {GeoJSONFeature} from '../util/vectortile_to_geojson';
22
import type {MapOptions} from '../ui/map';
33
import type {FeatureSelector} from '../style/style';
44
import type {ErrorEvent} from '../util/evented';
5-
import type {RequestTransformFunction} from '../util/mapbox';
5+
import type {RequestTransformFunction} from '../util/ajax';
66
import type {MapEvent, MapMouseEvent, MapTouchEvent} from '../ui/events';
77
import type {
88
Source,

src/ui/map.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ import type SourceCache from '../source/source_cache';
5454
import type {MapEventType, MapEventOf} from './events';
5555
import type {PointLike} from '../types/point-like';
5656
import type {FeatureState} from '../style-spec/expression/index';
57-
import type {AJAXError} from '../util/ajax';
58-
import type {RequestTransformFunction} from '../util/mapbox';
57+
import type {AJAXError, RequestTransformFunction} from '../util/ajax';
5958
import type {LngLatLike, LngLatBoundsLike} from '../geo/lng_lat';
6059
import type {CustomLayerInterface} from '../style/style_layer/custom_style_layer';
6160
import type {StyleImageInterface, StyleImageMetadata} from '../style/style_image';

src/util/ajax.ts

Lines changed: 75 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox_url';
1111
* @readonly
1212
* @enum {string}
1313
*/
14-
const ResourceType = {
14+
export const ResourceType = {
1515
Unknown: 'Unknown',
1616
Style: 'Style',
1717
Source: 'Source',
@@ -24,48 +24,97 @@ const ResourceType = {
2424
Model: 'Model'
2525
} as const;
2626

27-
export {ResourceType};
28-
2927
Object.freeze(ResourceType);
3028

3129
/**
32-
* A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.
30+
* The type of resource being requested in a {@link RequestTransformFunction}.
31+
*
32+
* @enum {string}
33+
* @property {string} Unknown An unknown resource.
34+
* @property {string} Style A style resource.
35+
* @property {string} Source A source resource.
36+
* @property {string} Tile A tile resource.
37+
* @property {string} Glyphs A glyphs resource.
38+
* @property {string} SpriteImage A sprite image resource.
39+
* @property {string} SpriteJSON A sprite JSON resource.
40+
* @property {string} Iconset An iconset resource.
41+
* @property {string} Image An image resource.
42+
* @property {string} Model A model resource.
43+
* @see {@link RequestTransformFunction}
44+
*/
45+
export type ResourceType = keyof typeof ResourceType;
46+
47+
/**
48+
* A `RequestParameters` object to be returned from the {@link Map} `transformRequest` option callback.
3349
* @typedef {Object} RequestParameters
3450
* @property {string} url The URL to be requested.
35-
* @property {Object} headers The headers to be sent with the request.
36-
* @property {string} method Request method `'GET' | 'POST' | 'PUT'`.
37-
* @property {string} body Request body.
38-
* @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`.
39-
* @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.
40-
* @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.
41-
* @property {string} referrerPolicy A string representing the request's referrerPolicy. For more information and possible values, see the [Referrer-Policy HTTP header page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy).
51+
* @property {Object} [headers] The headers to be sent with the request.
52+
* @property {string} [method='GET'] Request method, one of `'GET' | 'POST' | 'PUT'`.
53+
* @property {string} [body] Request body.
54+
* @property {string} [type='string'] Response body type to be returned, one of `'string' | 'json' | 'arrayBuffer'`.
55+
* @property {string} [credentials] Cross-origin credentials mode, one of `'same-origin' | 'include'`. Use `'include'` to send cookies with cross-origin requests.
56+
* @property {boolean} [collectResourceTiming=false] If `true`, Resource Timing API information will be collected for these transformed requests and returned in a `resourceTiming` property of relevant `data` events.
57+
* @property {string} [referrerPolicy] A string representing the request's referrerPolicy. For more information and possible values, see the [Referrer-Policy HTTP header page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy).
58+
* @see {@link RequestTransformFunction}
59+
* @see {@link ResourceType}
60+
*/
61+
export type RequestParameters = {
62+
url: string;
63+
headers?: Record<string, string>;
64+
method?: 'GET' | 'POST' | 'PUT';
65+
body?: string;
66+
type?: 'string' | 'json' | 'arrayBuffer';
67+
credentials?: 'same-origin' | 'include';
68+
collectResourceTiming?: boolean;
69+
referrerPolicy?: ReferrerPolicy;
70+
};
71+
72+
/**
73+
* A callback run before the Map makes a request for an external URL, used to rewrite the URL, attach headers, or set the credentials property for cross-origin requests.
74+
* The callback may return a {@link RequestParameters} object synchronously, or a `Promise` that resolves to one when the parameters need to be computed asynchronously — useful when each request needs a credential that has to be fetched at runtime, such as a [temporary access token](https://docs.mapbox.com/api/accounts/tokens/#create-a-temporary-token).
75+
*
76+
* @callback RequestTransformFunction
77+
* @param {string} url The URL to be requested.
78+
* @param {ResourceType} [resourceType] The type of resource being requested.
79+
* @param {Object} [options] Options including an `AbortSignal` that will be aborted if the request is cancelled.
80+
* @param {AbortSignal} [options.signal] An `AbortSignal` that will be aborted if the request is cancelled. Pass this to any async work (e.g. a `fetch` call) inside the callback so that the work is cancelled together with the request.
81+
* @returns {RequestParameters | Promise<RequestParameters>} The modified request parameters, or a `Promise` that resolves to them.
82+
*
4283
* @example
43-
* // use transformRequest to modify requests that begin with `http://myHost`
44-
* const map = new Map({
84+
* const map = new mapboxgl.Map({
4585
* container: 'map',
46-
* style: 'mapbox://styles/mapbox/streets-v11',
86+
* style: 'mapbox://styles/mapbox/standard',
4787
* transformRequest: (url, resourceType) => {
48-
* if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {
88+
* // Use `transformRequest` to modify requests that begin with `http://myHost`.
89+
* if (resourceType === 'Source' && url.startsWith('http://myHost')) {
4990
* return {
5091
* url: url.replace('http', 'https'),
5192
* headers: {'my-custom-header': true},
52-
* credentials: 'include' // Include cookies for cross-origin requests
93+
* credentials: 'include'
5394
* };
5495
* }
5596
* }
5697
* });
5798
*
99+
* @example
100+
* let tokenCache;
101+
* const map = new mapboxgl.Map({
102+
* container: 'map',
103+
* style: 'mapbox://styles/mapbox/standard',
104+
* transformRequest: async (url, resourceType, {signal}) => {
105+
* if (!tokenCache || Date.now() > new Date(tokenCache.expires).getTime()) {
106+
* const response = await fetch('https://example.com/token', {signal});
107+
* tokenCache = await response.json(); // {token, expires}
108+
* }
109+
* return {url, headers: {Authorization: `Bearer ${tokenCache.token}`}};
110+
* }
111+
* });
112+
*
113+
* @see {@link RequestParameters}
114+
* @see {@link ResourceType}
115+
* @see {@link Map}
58116
*/
59-
export type RequestParameters = {
60-
url: string;
61-
headers?: Record<string, string>;
62-
method?: 'GET' | 'POST' | 'PUT';
63-
body?: string;
64-
type?: 'string' | 'json' | 'arrayBuffer';
65-
credentials?: 'same-origin' | 'include';
66-
collectResourceTiming?: boolean;
67-
referrerPolicy?: ReferrerPolicy;
68-
};
117+
export type RequestTransformFunction = (url: string, resourceType?: ResourceType, options?: {signal?: AbortSignal}) => RequestParameters | Promise<RequestParameters>;
69118

70119
export type ResponseCallback<T> = (
71120
error?: Error | DOMException | AJAXError | null,

src/util/mapbox.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode
2121
import {postData, getData} from './ajax';
2222
import {getLivePerformanceMetrics} from '../util/live_performance';
2323

24-
import type {ResourceType as ResourceTypeEnum, RequestParameters} from './ajax';
24+
import type {ResourceType, RequestParameters, RequestTransformFunction} from './ajax';
2525
import type {LivePerformanceData} from '../util/live_performance';
2626
import type {TileJSON} from '../types/tilejson';
2727
import type {Map as MapboxMap} from "../ui/map";
@@ -35,9 +35,6 @@ const EXTENSION_RE = /\.[\w]+$/;
3535
const TILE_PATH_RE = /^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/;
3636
const ACCESS_TOKEN_PARAM_RE = /^access_token=(.*)$/;
3737

38-
export type ResourceType = keyof typeof ResourceTypeEnum;
39-
export type RequestTransformFunction = (url: string, resourceType?: ResourceType, options?: {signal?: AbortSignal}) => RequestParameters | Promise<RequestParameters>;
40-
4138
type UrlObject = {
4239
protocol: string;
4340
authority: string;

test/unit/source/raster_dem_tile_source.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import config from '../../../src/util/config';
1010
import type Tile from '../../../src/source/tile';
1111
import type Dispatcher from '../../../src/util/dispatcher';
1212
import type {Map as MapboxMap} from '../../../src/ui/map';
13-
import type {RequestTransformFunction} from '../../../src/util/mapbox';
13+
import type {RequestTransformFunction} from '../../../src/util/ajax';
1414
import type {RasterDEMSourceSpecification} from '../../../src/style-spec/types';
1515

1616
function createSource(options: Partial<RasterDEMSourceSpecification>, transformCallback?: RequestTransformFunction) {

0 commit comments

Comments
 (0)