-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathutils.ts
378 lines (336 loc) · 11.6 KB
/
utils.ts
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
import { camelCase, get, map, mapKeys, isPlainObject, mapValues } from 'lodash';
import { appConfig, rawLayers, rawReports, rawTables } from '.';
import {
AdminLevelDataLayerProps,
AnticipatoryActionLayerProps,
BoundaryLayerProps,
checkRequiredKeys,
CompositeLayerProps,
ImpactLayerProps,
LayerKey,
LayersMap,
LayerType,
PointDataLayerProps,
ReportType,
StaticRasterLayerProps,
StatsApi,
TableType,
WMSLayerProps,
} from './types';
// Typescript does not handle our configuration methods very well
// So we override the type of TableKey and ReportKey to make it more flexible.
export type TableKey = string;
export type ReportKey = string;
/**
* Check if a string is an explicitly defined report in reports.json
* @param reportsKey the string to check
*/
export const isReportsKey = (reportsKey: string): reportsKey is ReportKey =>
reportsKey in rawReports;
/**
* Check if a string is an explicitly defined table in tables.json
* @param tableKey the string to check
*/
export function isTableKey(tableKey: string): tableKey is TableKey {
return tableKey in rawTables;
}
function parseStatsApiConfig(maybeConfig: {
[key: string]: any;
}): StatsApi | undefined {
const config = mapKeys(maybeConfig, (_v, k) => camelCase(k));
if (checkRequiredKeys(StatsApi, config, true)) {
return config as StatsApi;
}
return undefined;
}
export function deepCamelCaseKeys(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(deepCamelCaseKeys);
}
if (isPlainObject(obj)) {
return mapValues(
mapKeys(obj, (_v, k) => camelCase(k)),
deepCamelCaseKeys,
);
}
return obj;
}
// CamelCase the keys inside the layer definition & validate config
export const getLayerByKey = (layerKey: LayerKey): LayerType => {
const rawDefinition = rawLayers[layerKey];
const definition: { id: LayerKey; type: LayerType['type'] } = {
id: layerKey,
type: rawDefinition.type as LayerType['type'],
// TODO - Transition to deepCamelCaseKeys
// but handle line-opacity and other special cases
...mapKeys(rawDefinition, (_v, k) => camelCase(k)),
};
const throwInvalidLayer = () => {
throw new Error(
`Found invalid layer definition for layer '${layerKey}'. Check console for more details.`,
);
};
switch (definition.type) {
case 'wms':
if (checkRequiredKeys(WMSLayerProps, definition, true)) {
return definition;
}
return throwInvalidLayer();
case 'admin_level_data':
if (checkRequiredKeys(AdminLevelDataLayerProps, definition, true)) {
if (typeof (definition.adminLevel as unknown) !== 'number') {
console.error(
`admin_level in layer ${definition.id} isn't a number.`,
);
return throwInvalidLayer();
}
return definition;
}
return throwInvalidLayer();
case 'impact':
if (checkRequiredKeys(ImpactLayerProps, definition, true)) {
return {
...definition,
api: definition.api && parseStatsApiConfig(definition.api),
};
}
return throwInvalidLayer();
case 'point_data':
if (checkRequiredKeys(PointDataLayerProps, definition, true)) {
return definition;
}
return throwInvalidLayer();
case 'boundary':
if (checkRequiredKeys(BoundaryLayerProps, definition, true)) {
return definition;
}
return throwInvalidLayer();
case 'static_raster':
if (checkRequiredKeys(StaticRasterLayerProps, definition, true)) {
return definition;
}
return throwInvalidLayer();
case 'composite':
if (!checkRequiredKeys(CompositeLayerProps, definition, true)) {
return throwInvalidLayer();
}
return definition;
case 'anticipatory_action':
if (!checkRequiredKeys(AnticipatoryActionLayerProps, definition, true)) {
return throwInvalidLayer();
}
return definition;
default:
// doesn't do anything, but it helps catch any layer type cases we forgot above compile time via TS.
// https://stackoverflow.com/questions/39419170/how-do-i-check-that-a-switch-block-is-exhaustive-in-typescript
// eslint-disable-next-line no-unused-vars
((_: never) => {})(definition.type);
throw new Error(
`Found invalid layer definition for layer '${layerKey}' (Unknown type '${definition.type}'). Check config/layers.json.`,
);
}
};
function verifyValidImpactLayer(
impactLayer: ImpactLayerProps,
layers: LayersMap,
) {
const layerIds = Object.keys(layers);
const throwIfInvalid = (key: 'hazardLayer' | 'baselineLayer') => {
if (!layerIds.includes(impactLayer[key])) {
throw new Error(
`Found invalid impact layer definition for ${impactLayer.id}: ${key}: '${impactLayer[key]}' does not match any of the layer ids in the config.`,
);
}
};
throwIfInvalid('hazardLayer');
throwIfInvalid('baselineLayer');
}
export const AAWindowKeys = ['Window 1', 'Window 2'] as const;
export const AALayerId = 'anticipatory_action';
export const LayerDefinitions: LayersMap = (() => {
const aaUrl = appConfig.anticipatoryActionUrl;
const AALayer: AnticipatoryActionLayerProps = {
id: AALayerId,
title: 'Anticipatory Action',
type: 'anticipatory_action',
opacity: 0.9,
};
const layers = Object.keys(rawLayers).reduce(
(acc, layerKey) => ({
...acc,
[layerKey]: getLayerByKey(layerKey as LayerKey),
}),
(aaUrl
? {
[AALayerId]: AALayer,
}
: {}) as LayersMap,
);
// Verify that the layers referenced by impact layers actually exist
Object.values(layers)
.filter((layer): layer is ImpactLayerProps => layer.type === 'impact')
.forEach(layer => verifyValidImpactLayer(layer, layers));
return layers;
})();
export function getBoundaryLayers(): BoundaryLayerProps[] {
return (
// eslint-disable-next-line fp/no-mutating-methods
Object.values(LayerDefinitions)
.filter((layer): layer is BoundaryLayerProps => layer.type === 'boundary')
.sort((a, b) => a.adminLevelCodes.length - b.adminLevelCodes.length)
);
}
// TODO - is this still relevant? @Amit do we have boundary files that we do not want displayed?
export function getDisplayBoundaryLayers(): BoundaryLayerProps[] {
const boundaryLayers = getBoundaryLayers();
const boundariesCount = boundaryLayers.length;
if (boundariesCount === 0) {
throw new Error(
'No boundary layer found. There should be at least one boundary layer defined in layers.json',
);
}
// check how many boundary layers defined in `layers.json`
// if they are more than one, use `defaultDisplayBoundaries` defined in `prism.json`
if (boundariesCount > 1) {
const defaultBoundaries: LayerKey[] = get(
appConfig,
'defaultDisplayBoundaries',
[],
);
const invalidDefaults = defaultBoundaries.filter(
id => !boundaryLayers.map(l => l.id).includes(id),
);
if (invalidDefaults.length > 0) {
throw new Error(
'Some of `defaultDisplayBoundaries` layer Ids are not valid. You must provide valid ids from `layers.json`',
);
}
// get override layers from override names without
// disrupting the order of which they are defined
// since the first is considered as default
// eslint-disable-next-line fp/no-mutating-methods
const defaultDisplayBoundaries = defaultBoundaries
.map(
// TODO - use a find?
id => boundaryLayers.filter(l => l.id === id)[0],
)
// order by admin level depth [decreasing]
.sort((a, b) => b.adminLevelCodes.length - a.adminLevelCodes.length);
if (defaultDisplayBoundaries.length === 0) {
throw new Error(
'Multiple boundary layers found. You must provide `defaultDisplayBoundaries` in prism.json',
);
}
return defaultDisplayBoundaries;
}
return boundaryLayers;
}
export function getBoundaryLayerSingleton(): BoundaryLayerProps {
return getDisplayBoundaryLayers()[0];
}
// Return a boundary layer with the specified adminLevel depth.
// TODO - better handle multicountry admin levels
export function getBoundaryLayersByAdminLevel(adminLevel?: number) {
if (adminLevel) {
const boundaryLayers = getBoundaryLayers();
const adminLevelBoundary = boundaryLayers.find(
boundaryLayer => boundaryLayer.adminLevelNames.length === adminLevel,
);
if (adminLevelBoundary) {
return adminLevelBoundary;
}
}
return getBoundaryLayerSingleton();
}
export const isPrimaryBoundaryLayer = (layer: BoundaryLayerProps) =>
(layer.type === 'boundary' && layer.isPrimary) ||
layer.id === getBoundaryLayerSingleton().id;
export function getWMSLayersWithChart(): WMSLayerProps[] {
return Object.values(LayerDefinitions).filter(
l => l.type === 'wms' && l.chartData,
) as WMSLayerProps[];
}
export const areChartLayersAvailable = getWMSLayersWithChart().length > 0;
const isValidReportsDefinition = (
maybeReport: object,
): maybeReport is ReportType =>
checkRequiredKeys(ReportType, maybeReport, true);
function isValidTableDefinition(maybeTable: object): maybeTable is TableType {
return checkRequiredKeys(TableType, maybeTable, true);
}
const getReportByKey = (key: ReportKey): ReportType => {
// Typescript does not handle our configuration methods very well
// So we temporarily override the type of rawReports to make it more flexible.
const reports = rawReports as Record<string, any>;
const rawDefinition = {
id: key,
...mapKeys(isReportsKey(key) ? reports[key] : {}, (_v, k) => camelCase(k)),
};
if (isValidReportsDefinition(rawDefinition)) {
return rawDefinition;
}
throw new Error(
`Found invalid report definition for report '${key}'. Check config/reports.json`,
);
};
function getTableByKey(key: TableKey): TableType {
// Typescript does not handle our configuration methods very well
// So we temporarily override the type of rawTables to make it more flexible.
const tables = rawTables as Record<string, any>;
const rawDefinition = {
id: key,
...mapKeys(isTableKey(key) ? tables[key] : {}, (_v, k) => camelCase(k)),
};
if (isValidTableDefinition(rawDefinition)) {
return rawDefinition;
}
throw new Error(
`Found invalid table definition for table '${key}'. Check config/tables.json`,
);
}
export const TableDefinitions = Object.keys(rawTables).reduce(
(acc, tableKey) => ({
...acc,
[tableKey]: getTableByKey(tableKey as TableKey),
}),
{},
) as { [key in TableKey]: TableType };
export const ReportsDefinitions = Object.keys(rawReports).reduce(
(acc, reportsKey) => ({
...acc,
[reportsKey]: getReportByKey(reportsKey as ReportKey),
}),
{},
) as { [key in ReportKey]: ReportType };
export const getCompositeLayers = (layer: LayerType): LayerType[] => {
const inputLayers =
layer.type === 'composite'
? (layer as CompositeLayerProps).inputLayers
: undefined;
const compositeLayersIds = inputLayers?.map(inputLayer => inputLayer.id);
if (compositeLayersIds?.length) {
const compositeLayers = map(
LayerDefinitions,
(value, key) =>
compositeLayersIds.includes(key as LayerType['type']) && value,
).filter(x => x);
return compositeLayers as LayerType[];
}
return [];
};
/**
* A utility function to get the STAC band parameter.
* WARNING: This function is fragile as it is using the _blended pattern in styles.
* @param additionalQueryParams - additional query parameters
* @returns the band parameter
*/
export const getStacBand = (
additionalQueryParams: Record<string, string> | undefined,
) => {
const { band, styles } =
(additionalQueryParams as {
styles?: string;
band?: string;
}) || {};
return band || styles?.replace('_blended', '');
};