utils/gis/fetch-gis-urls.js

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.dataFetch = exports.fetchAllGis = exports.fetchGisServices = exports.fetchGisFolders = void 0;
const axios_1 = __importDefault(require("axios"));
const https_1 = __importDefault(require("https"));
const crypto_1 = require("crypto");
/**
 * HTTPS agent for handling requests with legacy SSL support.
 *
 * @type {https.Agent}
 */
const agent = new https_1.default.Agent({
    rejectUnauthorized: false,
    secureOptions: crypto_1.constants.SSL_OP_LEGACY_SERVER_CONNECT // Allow legacy renegotiation
});
/**
 * Fetches GIS folders from a given base URL.
 *
 * @async
 * @param {string} baseUrl - The base URL for the GIS service.
 * @returns {Promise<string[]>} An array of service URLs within the folders.
 * @throws Will throw an error if the data cannot be fetched or processed.
 */
const fetchGisFolders = (baseUrl) => __awaiter(void 0, void 0, void 0, function* () {
    const jsonUrl = `${baseUrl}?f=pjson`;
    try {
        let typeUrls = [];
        let typeUrlArray = [];
        let typeUrlStrings = [];
        const results = yield axios_1.default.get(jsonUrl, { httpsAgent: agent });
        const data = results.data;
        const types = data.folders;
        for (let i = 0; i < types.length; i++) {
            typeUrls.push(`${baseUrl}/${types[i]}?f=pjson`);
        }
        const typeResponse = yield Promise.all(typeUrls.map(url => axios_1.default.get(url, { httpsAgent: agent })));
        const typeResult = typeResponse.map(result => result.data);
        typeResult.forEach((el) => {
            if (!el.error) {
                typeUrlArray.push(el.services);
            }
        });
        // Extract all service URLs
        const allTypeUrls = typeUrlArray.flatMap(serviceArray => serviceArray.map((service) => `${baseUrl}/${service.name}/${service.type}?f=pjson`));
        typeUrlStrings = allTypeUrls;
        return typeUrlStrings;
    }
    catch (error) {
        console.error('Error fetching folders or services', error);
        throw new Error('Failed to fetch GIS folders');
    }
});
exports.fetchGisFolders = fetchGisFolders;
/**
 * Fetches GIS services directly from a given base URL.
 *
 * @async
 * @param {string} baseUrl - The base URL for the GIS service.
 * @returns {Promise<string[]>} An array of service URLs within the services.
 * @throws Will throw an error if the data cannot be fetched or processed.
 */
const fetchGisServices = (baseUrl) => __awaiter(void 0, void 0, void 0, function* () {
    const jsonUrl = `${baseUrl}?f=pjson`;
    try {
        let typeUrls = [];
        const results = yield axios_1.default.get(jsonUrl, { httpsAgent: agent });
        const data = results.data;
        const types = data.services;
        for (let i = 0; i < types.length; i++) {
            typeUrls.push(`${baseUrl}/${types[i].name}/${types[i].type}?f=pjson`);
        }
        return typeUrls;
    }
    catch (error) {
        console.error('Error fetching services', error);
        throw new Error('Failed to fetch GIS services');
    }
});
exports.fetchGisServices = fetchGisServices;
/**
 * Fetches both GIS folders and services and combines their URLs.
 *
 * @async
 * @param {string} baseUrl - The base URL for the GIS service.
 * @returns {Promise<string[]>} An array of combined folder and service URLs.
 * @throws Will throw an error if either folders or services cannot be fetched.
 */
const fetchAllGis = (baseUrl) => __awaiter(void 0, void 0, void 0, function* () {
    const [folders, services] = yield Promise.all([
        (0, exports.fetchGisFolders)(baseUrl),
        (0, exports.fetchGisServices)(baseUrl)
    ]);
    return (folders || []).concat(services || []);
});
exports.fetchAllGis = fetchAllGis;
/**
 * Fetches all data layers from a GIS base URL.
 *
 * @async
 * @param {string} baseUrl - The base URL for the GIS service.
 * @returns {Promise<any[]>} An array of layer data.
 * @throws Will throw an error if data cannot be fetched or processed.
 */
const dataFetch = (baseUrl) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        let layers = [];
        const typeUrls = yield (0, exports.fetchAllGis)(baseUrl);
        if (!typeUrls || typeUrls.length === 0) {
            return [];
        }
        const typeResponse = yield Promise.all(typeUrls.map(url => axios_1.default.get(url, { httpsAgent: agent })));
        const typeResult = typeResponse.map(result => result.data);
        if (typeResult.length === 0) {
            return [];
        }
        // Extract layers from the responses
        for (let i = 0; i < typeResult.length; i++) {
            if (typeResult[i].layers) {
                layers.push(typeResult[i].layers);
            }
        }
        return layers;
    }
    catch (error) {
        console.error('Error fetching data from:', baseUrl, error);
        throw new Error('Failed to fetch GIS data');
    }
});
exports.dataFetch = dataFetch;