import { ColumnGeoJSONRecord, ColumnGeoJSONRecordWithID, type ColumnStatusCode, MacrostratRef, StratName, UnitLong, } from "@macrostrat/api-types"; import { addQueryString, joinURL } from "@macrostrat/ui-components"; import crossFetch from "cross-fetch"; import { feature } from "topojson-client"; import { geoArea } from "d3-geo"; function createScopedFetch(baseURL: string) { return function (url: string, options: RequestInit | undefined = undefined) { return crossFetch(baseURL + url, options); }; } const defaultFetch = createScopedFetch("https://macrostrat.org/api/v2"); /** Re-exported from `@macrostrat/api-types`, which owns the column shape, so * the two can't drift. */ export type { ColumnStatusCode }; /** Which projects a column request covers: one project id, several, a * comma-joined string of ids (the form the API itself takes, and the form the * web app's project filter produces), or the literal `"all"`. There is no * implicit default — see `ColumnFetchOptions`. */ export type ColumnProjectScope = number | number[] | string; /** The "Core columns" composite — the curated set the `/columns` API falls back * to when no project is named. Its flattened membership is exactly * `macrostrat.core_project_ids()`, so passing it reproduces the old implicit * default while saying so on the wire. */ export const CORE_COLUMNS_PROJECT_ID = 14; interface FetchBaseOptions { // The fetch implementation to use fetch?: (url: string, options?: RequestInit) => Promise; } export interface ColumnFetchOptions extends FetchBaseOptions { apiBaseURL?: string; /** Which projects to fetch: one numeric id, several, a comma-joined string of * ids, or the literal `"all"`. Required — there is no implicit default. The * API's own default, the "Core columns" composite, is * `CORE_COLUMNS_PROJECT_ID`; pass that to ask for it. * * This used to send `all=true` when no project was given, which `/columns` * silently ignores: the request fell through to the API's core-projects * default, so whole projects (GBDB's 28,951 columns among them) were absent * with nothing to indicate it. Callers now say what they mean. */ projectID: ColumnProjectScope; statusCode?: ColumnStatusCode | ColumnStatusCode[]; format?: "geojson" | "topojson" | "geojson_bare"; } export async function fetchAllColumns( options: ColumnFetchOptions, ): Promise { const { apiBaseURL, projectID, format = "topojson", statusCode, fetch = crossFetch, } = options; if (projectID == null) { throw new Error( 'fetchAllColumns requires an explicit projectID (a project id, a list of them, or "all")', ); } let args: any = { format, project_id: Array.isArray(projectID) ? projectID.join(",") : projectID, }; let _statusCode: string | undefined = undefined; if (Array.isArray(statusCode)) { _statusCode = statusCode.join(","); } else if (statusCode != null) { _statusCode = statusCode; } if (_statusCode != null) { args.status_code = _statusCode; } let url = "/columns"; if (apiBaseURL != null) { url = joinURL(apiBaseURL, url); } // Try with fetch url = addQueryString(url, args); const res = await fetch(url, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (res == null) { return []; } // Get JSON const data = await res.json(); return postProcessColumns(columnProcessors[format](data)); } function processGeoJSON(res) { return processGeoJSONBare(res?.success?.data); } function processGeoJSONBare(res) { return res?.features; } function processTopoJSON(res) { try { const { data } = res.success; const { features: f } = feature(data, data.objects.output) as any; return f; } catch (err) { console.error(err); return []; } } function postProcessColumns(columns) { return promoteColumnIDs( convertSmallAreasToPoints(removeFeaturesWithoutGeometry(columns)), ); } function promoteColumnIDs( features: ColumnGeoJSONRecord[], ): ColumnGeoJSONRecordWithID[] { return features.map((f, i) => { return { id: f.properties?.col_id, ...f, }; }); } function removeFeaturesWithoutGeometry(features) { return features.filter((f) => f.geometry != null); } function convertSmallAreasToPoints(features) { return features.map((f) => { // Point-located columns (`col_type = 'section'`) arrive from the API as // Points already, and there is no area to collapse. Without this guard the // zero-area test below passes and the ring indexing produces // `{ type: "Point", coordinates: undefined }`, which crashes anything that // streams the geometry — `geoCentroid` in the keyboard-navigation // triangulation, for one. if (f.geometry.type === "Point" || f.geometry.type === "MultiPoint") { return f; } // GeoArea takes a long time to run. We are really more worried about points that are zero-area if (geoArea(f.geometry) < 1e-8) { const centroid = f.geometry.coordinates[0][0]; f.geometry = { type: "Point", coordinates: centroid, }; } return f; }); } const columnProcessors = { topojson: processTopoJSON, geojson: processGeoJSON, geojson_bare: processGeoJSONBare, }; async function unwrapResponse(res) { if (res == null) { return null; } const resData = await res.json(); return resData["success"]["data"]; } export async function fetchLithologies(opts: FetchBaseOptions = {}) { const { fetch = defaultFetch } = opts; const res = await fetch("/defs/lithologies?all"); return await unwrapResponse(res); } export async function fetchIntervals( timescaleID: number | null, opts: FetchBaseOptions = {}, ) { const { fetch = defaultFetch } = opts; let url = `/defs/intervals`; if (timescaleID != null) { url += `?timescale_id=${timescaleID}`; } else { url += "?all"; } const res = await fetch(url); return await unwrapResponse(res); } export async function fetchEnvironments(opts: FetchBaseOptions = {}) { const { fetch = defaultFetch } = opts; const res = await fetch("/defs/environments?all"); return await unwrapResponse(res); } /** Lithology attributes (grain size, bedforms, colours…), `/defs/lithology_attributes`. */ export async function fetchLithAttributes(opts: FetchBaseOptions = {}) { const { fetch = defaultFetch } = opts; const res = await fetch("/defs/lithology_attributes?all"); return await unwrapResponse(res); } export async function fetchTimescales(opts: FetchBaseOptions = {}) { const { fetch = defaultFetch } = opts; const res = await fetch("/defs/timescales?all"); return await unwrapResponse(res); } export async function fetchRefs( refs: number[], opts: FetchBaseOptions = {}, ): Promise { const { fetch = defaultFetch } = opts; let url = `/defs/refs`; if (refs.length == 0) { return []; } url += "?ref_id=" + refs.join(","); const res = await fetch(url); return await unwrapResponse(res); } export async function fetchStratNames( names: number[], opts: FetchBaseOptions = {}, ): Promise { const { fetch = defaultFetch } = opts; let url = `/defs/strat_names`; if (names.length == 0) { return []; } url += "?strat_name_id=" + names.join(","); const res = await fetch(url); return await unwrapResponse(res); } export type ColumnData = { units: UnitLong[]; columnID: number; }; export async function fetchUnits( columns: number[], opts: FetchBaseOptions = {}, ): Promise { const { fetch = defaultFetch } = opts; const params = new URLSearchParams(); params.append("response", "long"); if (columns.length == 0) { return []; } const col_string = columns.map((column) => column.toString()).join(","); params.append("col_id", col_string); const res = await fetch("/units" + "?" + params.toString()); const data = await res.json(); if (!data.success) { throw new Error("Failed to fetch column units"); } const units = data.success.data; const unitsMap = new Map(); for (const unit of units) { const colID = unit.col_id; let unitsArray = unitsMap.get(colID); if (unitsArray == null) { unitsMap.set(colID, [unit]); } else { unitsArray.push(unit); } } const result: ColumnData[] = []; for (const colID of columns) { result.push({ columnID: colID, units: unitsMap.get(colID) || [] }); } return result; } export async function fetchColumnUnits( col_id: number, opts: FetchBaseOptions = {}, ): Promise { const { fetch = defaultFetch } = opts; const params = new URLSearchParams(); params.append("response", "long"); params.append("col_id", col_id.toString()); const res = await fetch("/units" + "?" + params.toString()); const data = await res.json(); if (!data.success) { throw new Error("Failed to fetch column units"); } const units = data.success.data; return { columnID: col_id, units }; }