forked from camptocamp/ogc-client
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathendpoint.ts
More file actions
877 lines (835 loc) · 30.5 KB
/
endpoint.ts
File metadata and controls
877 lines (835 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
import {
checkHasConnectedSystems,
checkHasEnvironmentalDataRetrieval,
checkHasFeatures,
checkHasRecords,
checkStyleConformance,
checkTileConformance,
parseBaseCollectionInfo,
parseBasicStyleInfo,
parseCollectionParameters,
parseCollections,
parseConformance,
parseEndpointInfo,
parseFullStyleInfo,
parseTileMatrixSets,
} from './info.js';
import {
ConformanceClass,
OgcApiCollectionInfo,
OgcApiCollectionItem,
OgcApiDocument,
OgcApiEndpointInfo,
OgcApiStyleMetadata,
OgcApiStylesDocument,
OgcStyleBrief,
OgcStyleFull,
TileMatrixSet,
} from './model.js';
import {
fetchCollectionRoot,
fetchDocument,
fetchLink,
fetchRoot,
getLinks,
getLinkUrl,
hasLinks,
} from './link-utils.js';
import { EndpointError } from '../shared/errors.js';
import {
BoundingBox,
CrsCode,
DateTimeParameter,
MimeType,
} from '../shared/models.js';
import {
isMimeTypeGeoJson,
isMimeTypeJson,
isMimeTypeJsonFg,
} from '../shared/mime-type.js';
import { getBaseUrl, getChildPath } from '../shared/url-utils.js';
import EDRQueryBuilder from './edr/url_builder.js';
// Type-only import keeps the CSAPI module out of the main bundle's static
// dependency graph (the runtime values from `./csapi/factory.js` and
// `./csapi/helpers.js` are loaded via dynamic import inside `csapi()` to
// preserve the dependency-edge contract from issue #122 / commit 20a35d2).
import type CSAPIQueryBuilder from './csapi/url_builder.js';
import type { CSAPICollectionRef } from './csapi/model.js';
/**
* Represents an OGC API endpoint advertising various collections and services.
*/
export default class OgcApiEndpoint {
// these are cached results because the getters rely on HTTP requests; to avoid
// unhandled promise rejections the getters are evaluated lazily
private root_: Promise<OgcApiDocument>;
private conformance_: Promise<OgcApiDocument>;
private data_: Promise<OgcApiDocument | null>;
private tileMatrixSetsFull_: Promise<TileMatrixSet[]>;
private styles_: Promise<OgcApiStylesDocument>;
private collection_id_to_edr_builder_: Map<string, EDRQueryBuilder> =
new Map();
private get root(): Promise<OgcApiDocument> {
if (!this.root_) {
this.root_ = fetchRoot(this.baseUrl).catch((e) => {
throw new EndpointError(`The endpoint appears non-conforming, the following error was encountered:
${e.message}`);
});
}
return this.root_;
}
private get conformance(): Promise<OgcApiDocument> {
if (!this.conformance_) {
this.conformance_ = this.root.then((root) =>
fetchLink(
root,
['conformance', 'http://www.opengis.net/def/rel/ogc/1.0/conformance'],
this.baseUrl
)
);
}
return this.conformance_;
}
private get collectionsUrl(): Promise<string | null> {
return this.root.then((root) =>
getLinkUrl(
root,
['data', 'http://www.opengis.net/def/rel/ogc/1.0/data'],
this.baseUrl
)
);
}
private get data(): Promise<OgcApiDocument> {
if (!this.data_) {
this.data_ = this.collectionsUrl.then((url) => {
if (!url) return null;
return fetchDocument(url).then(async (data) => {
// check if there's a collection in the path; if yes, keep only this one
const singleCollection = await fetchCollectionRoot(this.baseUrl);
if (singleCollection !== null && Array.isArray(data.collections)) {
data.collections = data.collections.filter(
(collection) => collection.id === singleCollection.id
);
}
return data;
});
});
}
return this.data_;
}
private get tileMatrixSetsFull(): Promise<TileMatrixSet[]> {
if (!this.tileMatrixSetsFull_) {
this.tileMatrixSetsFull_ = this.root.then(async (root) => {
if (!(await this.hasTiles)) return [];
return fetchLink(
root,
['http://www.opengis.net/def/rel/ogc/1.0/tiling-schemes'],
this.baseUrl
).then(parseTileMatrixSets);
});
}
return this.tileMatrixSetsFull_;
}
private get styles(): Promise<OgcApiStylesDocument> {
if (!this.styles_) {
this.styles_ = this.root.then(async (root) => {
if (!(await this.hasStyles)) return undefined;
return fetchLink(
root,
['styles', 'http://www.opengis.net/def/rel/ogc/1.0/styles'],
this.baseUrl
) as unknown as OgcApiStylesDocument;
});
}
return this.styles_;
}
/**
* Creates a new OGC API endpoint.
* @param baseUrl Base URL used to query the endpoint. Note that this can point to nested
* documents inside the endpoint, such as `/collections`, `/collections/items` etc.
*/
constructor(private baseUrl: string) {}
/**
* A Promise which resolves to the endpoint information.
*/
get info(): Promise<OgcApiEndpointInfo> {
return this.root.then(parseEndpointInfo);
}
/**
* A Promise which resolves to an array of conformance classes.
*/
get conformanceClasses(): Promise<ConformanceClass[]> {
return this.conformance.then(parseConformance);
}
/**
* A Promise which resolves to an array of all collection identifiers as strings.
*/
get allCollections(): Promise<
{
name: string;
hasRecords?: boolean;
hasFeatures?: boolean;
hasVectorTiles?: boolean;
hasMapTiles?: boolean;
hasDataQueries?: boolean;
hasConnectedSystems?: boolean;
}[]
> {
return this.data.then((dataDocument) =>
dataDocument ? parseCollections(dataDocument) : []
);
}
/**
* A Promise which resolves to an array of records collection identifiers as strings.
*/
get recordCollections(): Promise<string[]> {
return Promise.all([this.data, this.hasRecords])
.then(([data, hasRecords]) => (hasRecords ? data : { collections: [] }))
.then(parseCollections)
.then((collections) => collections.filter((c) => c.hasRecords))
.then((collections) => collections.map((collection) => collection.name));
}
/**
* A Promise which resolves to an array of feature collection identifiers as strings.
*/
get featureCollections(): Promise<string[]> {
return Promise.all([this.data, this.hasFeatures])
.then(([data, hasFeatures]) => (hasFeatures ? data : { collections: [] }))
.then(parseCollections)
.then((collections) => collections.filter((c) => c.hasFeatures))
.then((collections) => collections.map((collection) => collection.name));
}
get edrCollections(): Promise<string[]> {
return Promise.all([this.data, this.hasEnvironmentalDataRetrieval])
.then(([data, hasEDR]) => (hasEDR ? data : { collections: [] }))
.then(parseCollections)
.then((collections) => collections.filter((c) => c.hasDataQueries))
.then((collections) => collections.map((collection) => collection.name));
}
/**
* A Promise which resolves to an array of Connected Systems collection
* identifiers as strings.
*
* Only collections whose links advertise CSAPI resource relations
* (e.g., `ogc-cs:systems`, `ogc-cs:datastreams`) are included.
*
* @example
* ```ts
* const endpoint = await new OgcApiEndpoint('https://api.example.com');
* const collections = await endpoint.csapiCollections;
* // => ['weather-stations', 'river-gauges']
* ```
*
* @see {@link hasConnectedSystems} to check feature support first
* @see https://docs.ogc.org/is/23-001/23-001.html
*/
get csapiCollections(): Promise<string[]> {
return Promise.all([this.data, this.hasConnectedSystems])
.then(([data, hasCSAPI]) => (hasCSAPI ? data : { collections: [] }))
.then(parseCollections)
.then((collections) => collections.filter((c) => c.hasConnectedSystems))
.then((collections) => collections.map((collection) => collection.name));
}
/**
* A Promise which resolves to an array of vector tile collection identifiers as strings.
*/
get vectorTileCollections(): Promise<string[]> {
return Promise.all([this.data, this.hasTiles])
.then(([data, hasTiles]) => (hasTiles ? data : { collections: [] }))
.then(parseCollections)
.then((collections) =>
collections.filter((collection) => collection.hasVectorTiles)
)
.then((collections) => collections.map((collection) => collection.name));
}
/**
* A Promise which resolves to an array of map tile collection identifiers as strings.
*/
get mapTileCollections(): Promise<string[]> {
return Promise.all([this.data, this.hasTiles])
.then(([data, hasTiles]) => (hasTiles ? data : { collections: [] }))
.then(parseCollections)
.then((collections) =>
collections.filter((collection) => collection.hasMapTiles)
)
.then((collections) => collections.map((collection) => collection.name));
}
/**
* A Promise which resolves to a boolean indicating whether the endpoint offer tiles.
*/
get hasTiles(): Promise<boolean> {
return this.conformanceClasses.then(checkTileConformance);
}
/**
* A Promise which resolves to a boolean indicating whether the endpoint offer styles.
*/
get hasStyles(): Promise<boolean> {
return this.conformanceClasses.then(checkStyleConformance);
}
/**
* A Promise which resolves to a boolean indicating whether the endpoint offer feature collections.
*/
get hasFeatures(): Promise<boolean> {
return Promise.all([
this.data.then((data) => (data ? data.collections : [])),
this.conformanceClasses,
]).then(checkHasFeatures);
}
/**
* A Promise which resolves to a boolean indicating whether the endpoint offer record collections.
*/
get hasRecords(): Promise<boolean> {
return Promise.all([
this.data.then((data) => (data ? data.collections : [])),
this.conformanceClasses,
]).then(checkHasRecords);
}
/**
* A Promise which resolves to a boolean indicating whether the endpoint offers environmental data retrieval (EDR) queries.
*/
get hasEnvironmentalDataRetrieval(): Promise<boolean> {
return Promise.all([this.conformanceClasses]).then(
checkHasEnvironmentalDataRetrieval
);
}
/**
* A Promise which resolves to a boolean indicating whether the endpoint
* offers Connected Systems (CSAPI) resources.
*
* Checks the endpoint's conformance classes for any of the CSAPI Part 1
* or Part 2 conformance URIs.
*
* @example
* ```ts
* const endpoint = await new OgcApiEndpoint('https://api.example.com');
* if (await endpoint.hasConnectedSystems) {
* const builder = await createCSAPIBuilder(endpoint, 'weather-stations');
* // ... build CSAPI queries
* }
* ```
*
* @see Use createCSAPIBuilder via '@camptocamp/ogc-client/csapi'
* @see {@link csapiCollections} to list available collections
* @see https://docs.ogc.org/is/23-001/23-001.html
*/
get hasConnectedSystems(): Promise<boolean> {
return Promise.all([this.conformanceClasses]).then(
checkHasConnectedSystems
);
}
/*
* A Promise which resolves to a class for constructing EDR queries
*/
public async edr(collection_id: string): Promise<EDRQueryBuilder> {
if (!this.hasEnvironmentalDataRetrieval) {
throw new EndpointError('Endpoint does not support EDR');
}
const cache = this.collection_id_to_edr_builder_;
if (cache.has(collection_id)) {
return cache.get(collection_id);
}
const collection = await this.getCollectionInfo(collection_id);
const result = new EDRQueryBuilder(collection);
cache.set(collection_id, result);
return result;
}
/**
* Returns a CSAPI (Connected Systems) query builder scoped to a single
* collection. Mirrors {@link edr} for the CSAPI capability.
*
* @param collectionId - The collection identifier to build queries against.
* @returns A {@link CSAPIQueryBuilder} for the given collection.
* @throws {EndpointError} If the endpoint does not advertise Connected
* Systems support, or if the collection metadata cannot be fetched.
*
* @remarks
* Loads `./csapi/factory.js` and `./csapi/helpers.js` via **dynamic**
* import to keep CSAPI out of the main entry-point bundle for consumers
* who never call this method. Static imports re-introduce the
* dependency edge that issue #122 (commit `20a35d2`) deliberately
* removed — do not change to static.
*
* @see {@link edr} for the analogous EDR builder factory
* @see https://docs.ogc.org/is/23-001/23-001.html
* @see https://docs.ogc.org/is/23-002/23-002.html
*/
public async csapi(collectionId: string): Promise<CSAPIQueryBuilder> {
if (!(await this.hasConnectedSystems)) {
throw new EndpointError('Endpoint does not support Connected Systems');
}
let collectionDoc: OgcApiDocument;
let rootDoc: OgcApiDocument;
try {
collectionDoc = await this.getCollectionDocument(collectionId);
rootDoc = await this.root;
} catch (e) {
if (e instanceof EndpointError) throw e;
throw new EndpointError(
`Failed to initialize CSAPI builder for collection '${collectionId}': ${
e instanceof Error ? e.message : String(e)
}`
);
}
// Shape the raw collection document into a value-typed
// CSAPICollectionRef. We do not route through getCollectionInfo()
// because parseBaseCollectionInfo strips `links` via destructuring
// (info.ts:130), and CSAPIQueryBuilder.extractAvailableResources
// depends on collection.links to discover supported CSAPI resources.
const collection: CSAPICollectionRef = {
id:
typeof collectionDoc.id === 'string' ? collectionDoc.id : collectionId,
title:
typeof collectionDoc.title === 'string'
? collectionDoc.title
: undefined,
links: Array.isArray(collectionDoc.links) ? collectionDoc.links : [],
};
const rootLinks = Array.isArray(rootDoc?.links) ? rootDoc.links : [];
const { createCSAPIBuilder } = await import('./csapi/factory.js');
const { scanCsapiLinks } = await import('./csapi/helpers.js');
return createCSAPIBuilder(collection, scanCsapiLinks(rootLinks));
}
/**
* Retrieve the tile matrix sets identifiers advertised by the endpoint. Empty if tiles are not supported
*/
get tileMatrixSets(): Promise<string[]> {
return this.tileMatrixSetsFull.then((sets) => sets.map((set) => set.id));
}
private getCollectionDocument(collectionId: string): Promise<OgcApiDocument> {
return Promise.all([this.allCollections, this.data])
.then(([collections, data]) => {
if (!collections.find((collection) => collection.name === collectionId))
throw new EndpointError(`Collection not found: ${collectionId}`);
return data.collections.find(
(collection) => collection.id === collectionId
);
})
.then(async (collection) => {
// if a self link is there, use it!
if (hasLinks(collection, ['self'])) {
return fetchLink(collection, 'self', this.baseUrl);
}
// otherwise build a URL for the collection
return fetchDocument(
getChildPath(await this.collectionsUrl, collectionId)
);
});
}
private async getStyleMetadataDocument(
styleId: string,
collectionId?: string
): Promise<OgcApiDocument> {
const doc = collectionId
? await this.getCollectionDocument(collectionId)
: await this.root;
const stylesLinkJson = getLinkUrl(
doc as OgcApiDocument,
['styles', 'http://www.opengis.net/def/rel/ogc/1.0/styles'],
this.baseUrl,
'application/json'
);
const stylesLink = getLinkUrl(
doc as OgcApiDocument,
['styles', 'http://www.opengis.net/def/rel/ogc/1.0/styles'],
this.baseUrl
);
const styleData = (await fetchDocument(
stylesLinkJson ?? stylesLink
)) as OgcApiStylesDocument;
if (!styleData.styles.some((style) => style.id === styleId)) {
throw new EndpointError(`Style not found: "${styleId}".`);
}
const styleDoc = styleData?.styles?.find((style) => style.id === styleId);
if (hasLinks(styleDoc as OgcApiDocument, ['describedby'])) {
return fetchLink(styleDoc as OgcApiDocument, 'describedby', this.baseUrl);
} else {
// fallback: return style document
return styleDoc as OgcApiDocument;
}
}
/**
* Returns a promise resolving to a document describing the specified collection.
* @param collectionId
*/
async getCollectionInfo(collectionId: string): Promise<OgcApiCollectionInfo> {
const collectionDoc = await this.getCollectionDocument(collectionId);
const baseInfo = parseBaseCollectionInfo(collectionDoc);
const [queryables, sortables, tilesetsVector, tilesetsMap] =
await Promise.all([
fetchLink(
collectionDoc,
['queryables', 'http://www.opengis.net/def/rel/ogc/1.0/queryables'],
this.baseUrl
)
.then(parseCollectionParameters)
.catch(() => []),
fetchLink(
collectionDoc,
['sortables', 'http://www.opengis.net/def/rel/ogc/1.0/sortables'],
this.baseUrl
)
.then(parseCollectionParameters)
.catch(() => []),
fetchLink(
collectionDoc,
['http://www.opengis.net/def/rel/ogc/1.0/tilesets-vector'],
this.baseUrl
)
.then((tilesetDoc) => tilesetDoc.tilesets)
.catch(() => []),
fetchLink(
collectionDoc,
['http://www.opengis.net/def/rel/ogc/1.0/tilesets-map'],
this.baseUrl
)
.then((tilesetDoc) => tilesetDoc.tilesets)
.catch(() => []),
]);
const tileMatrixSetsFull = await this.tileMatrixSetsFull;
const supportedTileMatrixSets = tilesetsVector
.map(
(tileset) =>
tileMatrixSetsFull.find((set) => set.uri === tileset.tileMatrixSetURI)
?.id
)
.filter(Boolean);
const firstTilesetVector = tilesetsVector[0];
let vectorTileFormats = [];
if (firstTilesetVector) {
const tilesetUrl = getLinkUrl(
firstTilesetVector,
'self',
this.baseUrl,
undefined,
true
);
const tilesetDoc = await fetchDocument(tilesetUrl);
vectorTileFormats = getLinks(tilesetDoc, 'item').map((link) => link.type);
}
const firstTilesetMap = tilesetsMap[0];
let mapTileFormats = [];
if (firstTilesetMap) {
const tilesetUrl = getLinkUrl(
firstTilesetMap,
'self',
this.baseUrl,
undefined,
true
);
const tilesetDoc = await fetchDocument(tilesetUrl);
mapTileFormats = getLinks(tilesetDoc, 'item').map((link) => link.type);
}
return {
...baseInfo,
queryables,
sortables,
mapTileFormats,
vectorTileFormats,
supportedTileMatrixSets,
};
}
/**
* Returns a promise resolving to an array of items from a collection with the given query parameters.
* @param collectionId
* @param [limit]
* @param [offset]
* @param [skipGeometry]
* @param [sortBy]
* @param [boundingBox]
* @param [properties]
* @param [dateTime] See OGC requirement: https://docs.ogc.org/is/17-069r3/17-069r3.html#_parameter_datetime
* @param [query] Freeform query string appended to the URL when fetching items (will be URL-encoded if necessary)
*/
getCollectionItems(
collectionId: string,
limit: number = 10,
offset: number = 0,
skipGeometry: boolean = null,
sortBy: string[] = null,
boundingBox: BoundingBox = null,
properties: string[] = null,
dateTime: DateTimeParameter = null,
query: string = null
): Promise<OgcApiCollectionItem[]> {
return this.getCollectionItemsUrl(collectionId, {
extent: boundingBox,
limit: limit !== null ? limit : undefined,
offset: offset !== null ? offset : undefined,
skipGeometry: skipGeometry !== null ? skipGeometry : undefined,
sortBy: sortBy !== null ? sortBy : undefined,
properties: properties !== null ? properties : undefined,
dateTime: dateTime !== null ? dateTime : undefined,
query: query !== null ? query : undefined,
asJson: true,
})
.then(fetchDocument)
.then((doc) => doc.features as OgcApiCollectionItem[]);
}
/**
* Returns a promise resolving to a specific item from a collection.
* @param collectionId
* @param itemId
*/
getCollectionItem(
collectionId: string,
itemId: string
): Promise<OgcApiCollectionItem> {
return this.getCollectionDocument(collectionId)
.then((collectionDoc) => {
const url = new URL(
getLinkUrl(collectionDoc, 'items', this.baseUrl),
getBaseUrl()
);
url.pathname += `/${itemId}`;
return url.toString();
})
.then(fetchDocument<OgcApiCollectionItem>);
}
/**
* Asynchronously retrieves a URL for the items of a specified collection, with optional query parameters.
* @param collectionId - The unique identifier for the collection.
* @param options - An object containing optional parameters:
* - query: Additional query parameters to be included in the URL.
* - asJson: Will query items as GeoJson or JSON-FG if available; takes precedence on `outputFormat`.
* - outputFormat: The MIME type for the output format.
* - limit: The maximum number of features to include.
* - extent: Bounding box to limit the features.
* - offset: Pagination offset for the returned results.
* - outputCrs: Coordinate Reference System code for the output.
* - extentCrs: Coordinate Reference System code for the bounding box.
* - skipGeometry: whether to include geometry in the response or not
* - sortBy: attributes by which to sort
* - properties: which properties to include in the response.
* - dateTime: Date parameter, either as a Date object or a range object with start and end properties.
* @returns A promise that resolves to the URL as a string or rejects if an error occurs.
*/
getCollectionItemsUrl(
collectionId: string,
options: {
query?: string;
asJson?: boolean;
outputFormat?: MimeType;
limit?: number;
offset?: number;
outputCrs?: CrsCode;
extent?: BoundingBox;
extentCrs?: CrsCode;
skipGeometry?: boolean;
sortBy?: string[];
properties?: string[];
dateTime?: DateTimeParameter;
} = {}
): Promise<string> {
return this.getCollectionDocument(collectionId)
.then((collectionDoc) => {
const baseUrl = this.baseUrl || '';
const itemLinks = getLinks(collectionDoc, 'items', undefined, true);
let linkWithFormat = itemLinks.find(
(link) => link.type === options?.outputFormat
);
let url: URL;
if (options.asJson) {
// try json-fg, geojson and json
linkWithFormat =
itemLinks.find((link) => isMimeTypeJsonFg(link.type)) ||
itemLinks.find((link) => isMimeTypeGeoJson(link.type)) ||
itemLinks.find((link) => isMimeTypeJson(link.type));
}
if (options?.outputFormat && !linkWithFormat) {
// do not prevent using this output format, because it still might work! but give a warning at least
console.warn(
`[ogc-client] The following output format type was not found in the collection '${collectionId}': ${options.outputFormat}`
);
url = new URL(itemLinks[0].href, baseUrl);
url.searchParams.set('f', options.outputFormat);
} else if (linkWithFormat) {
url = new URL(linkWithFormat.href, baseUrl);
} else {
url = new URL(itemLinks[0].href, baseUrl);
}
if (options.limit !== undefined)
url.searchParams.set('limit', options.limit.toString());
if (options.offset !== undefined)
url.searchParams.set('offset', options.offset.toString());
if (options.skipGeometry !== undefined)
url.searchParams.set('skipGeometry', options.skipGeometry.toString());
if (options.sortBy !== undefined)
url.searchParams.set('sortby', options.sortBy.join(',').toString());
if (options.properties !== undefined)
url.searchParams.set(
'properties',
options.properties.join(',').toString()
);
if (options.dateTime !== undefined) {
const dateTime = options.dateTime;
url.searchParams.set(
'datetime',
dateTime instanceof Date
? dateTime.toISOString()
: `${'start' in dateTime ? dateTime.start.toISOString() : '..'}/${
'end' in dateTime ? dateTime.end.toISOString() : '..'
}`
);
}
if (options.outputCrs !== undefined)
url.searchParams.set('crs', options.outputCrs);
if (options.extent?.length > 0)
url.searchParams.set('bbox', options.extent.join(',').toString());
if (options.extentCrs !== undefined)
url.searchParams.set('bbox-crs', options.extentCrs);
if (options.query !== undefined)
url.search += (url.search ? '&' : '') + encodeURI(options.query);
return url.toString();
})
.catch((error) => {
console.error('Error fetching collection items URL:', error);
throw error;
});
}
/**
* Asynchronously retrieves a URL to render a specified collection as vector tiles, with a given tile matrix set.
* @param collectionId - The unique identifier for the collection.
* @param tileMatrixSet - The identifier of the tile matrix set to use. Default is 'WebMercatorQuad'.
*/
getVectorTilesetUrl(
collectionId: string,
tileMatrixSet = 'WebMercatorQuad'
): Promise<string> {
return this.getCollectionDocument(collectionId)
.then(async (collectionDoc) => {
const collectionTilesLink = getLinkUrl(
collectionDoc,
'http://www.opengis.net/def/rel/ogc/1.0/tilesets-vector',
this.baseUrl
);
const collectionTiles = await fetchDocument(collectionTilesLink);
const matrixSet = (await this.tileMatrixSetsFull).find(
(set) => set.id === tileMatrixSet
);
if (!matrixSet) {
throw new Error(
`The following tile matrix set does not exist on this endpoint: '${tileMatrixSet}'.`
);
}
const tileset = collectionTiles.tilesets.find(
(tileset) => tileset.tileMatrixSetURI === matrixSet.uri
);
if (!tileset) {
throw new Error(
`The collection '${collectionId}' does not support the tile matrix set '${tileMatrixSet}'.`
);
}
const tilesetUrl = getLinkUrl(tileset, 'self', this.baseUrl);
if (!tilesetUrl) {
throw new Error('No links found for the tileset');
}
return tilesetUrl;
})
.catch((error) => {
console.error('Error fetching collection tileset URL:', error.message);
throw error;
});
}
/**
* Asynchronously retrieves a URL to render a specified collection as map tiles, with a given tile matrix set.
* @param collectionId - The unique identifier for the collection.
* @param tileMatrixSet - The identifier of the tile matrix set to use. Default is 'WebMercatorQuad'.
*/
getMapTilesetUrl(
collectionId: string,
tileMatrixSet = 'WebMercatorQuad'
): Promise<string> {
return this.getCollectionDocument(collectionId)
.then(async (collectionDoc) => {
const collectionTilesLink = getLinkUrl(
collectionDoc,
'http://www.opengis.net/def/rel/ogc/1.0/tilesets-map',
this.baseUrl
);
const collectionTiles = await fetchDocument(collectionTilesLink);
const matrixSet = (await this.tileMatrixSetsFull).find(
(set) => set.id === tileMatrixSet
);
if (!matrixSet) {
throw new Error(
`The following tile matrix set does not exist on this endpoint: '${tileMatrixSet}'.`
);
}
const tileset = collectionTiles.tilesets.find(
(tileset) => tileset.tileMatrixSetURI === matrixSet.uri
);
if (!tileset) {
throw new Error(
`The collection '${collectionId}' does not support the tile matrix set '${tileMatrixSet}'.`
);
}
const tilesetUrl = getLinkUrl(tileset, 'self', this.baseUrl);
if (!tilesetUrl) {
throw new Error('No links found for the tileset');
}
return tilesetUrl;
})
.catch((error) => {
console.error('Error fetching collection tileset URL:', error.message);
throw error;
});
}
/**
* A Promise which resolves to an array of all style items. This includes the supported style formats.
* @param collectionId - Optional unique identifier for the collection.
*/
async allStyles(collectionId?: string): Promise<OgcStyleBrief[]> {
const doc = collectionId
? await this.getCollectionDocument(collectionId)
: await this.root;
const stylesLink = getLinkUrl(
doc as OgcApiDocument,
['styles', 'http://www.opengis.net/def/rel/ogc/1.0/styles'],
this.baseUrl,
undefined,
true
);
const styleData = (await fetchDocument(stylesLink)) as OgcApiStylesDocument;
return styleData.styles.map(parseBasicStyleInfo);
}
/**
* Returns a promise resolving to a document describing the style. Looks for a relation of type
* "describedby" to fetch metadata. If no relation is found, only basic info will be returned.
* @param styleId - The style identifier
* @param collectionId - Optional unique identifier for the collection.
*/
async getStyle(
styleId: string,
collectionId?: string
): Promise<OgcStyleFull | OgcStyleBrief> {
const metadataDoc = await this.getStyleMetadataDocument(
styleId,
collectionId
);
if (!metadataDoc?.stylesheets) {
return parseBasicStyleInfo(metadataDoc as OgcApiStyleMetadata);
}
return parseFullStyleInfo(metadataDoc as OgcApiStyleMetadata);
}
/**
* Returns a promise resolving to a stylesheet URL for a given style and type.
* @param styleId - The style identifier
* @param mimeType - Stylesheet MIME type
* @param collectionId - Optional unique identifier for the collection.
*/
async getStylesheetUrl(
styleId: string,
mimeType: string,
collectionId?: string
): Promise<string> {
const stylesDoc = await this.getStyleMetadataDocument(
styleId,
collectionId
);
if (stylesDoc.stylesheets) {
return (stylesDoc as OgcApiStyleMetadata)?.stylesheets?.find(
(s) => s.link.type === mimeType && s.link.rel === 'stylesheet'
)?.link?.href;
}
return getLinkUrl(stylesDoc, 'stylesheet', this.baseUrl, mimeType, true);
}
}