Source: map/importer/binder/IndexBinder.js

import { createVEFLayerConfig } from "../../../utils/universal/ogc/createVEFLayerConfig.js";

export { IndexBinder }

/**
 * IndexBinder for loading layer-metadata from the search index.
 *
 * @author rhess <robin.hess@awi.de>
 * 
 * @memberof vef.map.importer.binder
 *
 */
class IndexBinder {

    constructor(url, indices) {
        this.url = url || "https://marine-data.de/rest/search/"
        this.indices = indices || ["service2"];
    }

    fetch(params) {
        return new Promise((resolve, reject) => {
            const content = JSON.stringify(Object.assign({
                indices: this.indices,
                types: [],
                sorts: [],
                facets: [],
                excludes: [],
                includes: [],
                queryFacets: {},
                queryGeometries: {},
                offset: 0,
                hits: 0,
                query: ""
            }, params || {}));

            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        const json = JSON.parse(xhr.responseText)
                        const promises = [];
                        json.records.forEach(record => {
                            promises.push(record);
                        });
                        Promise.all(promises).then(() => {
                            resolve(json);
                        })
                    } else {
                        reject();
                    }
                }
            };
            xhr.open("POST", this.url, true);
            xhr.setRequestHeader('Accept', 'application/json;charset=UTF-8');
            xhr.setRequestHeader('content-type', 'application/json;charset=UTF-8');
            xhr.send(content);
        });
    }


    /**
     * Get layers from the catalog queried by the given options
     *
     * @param {Object[]} params 
     * @returns {Promise} promise returns an array of layers
     */
    async fetchLayers(params) {
        const response = await this.fetch(params);
        const layers = {};
        for (let i = 0; i < response.records.length; ++i) {
            const layer = await createVEFLayerConfig(response.records[i]);
            if (layer) layers[response.records[i].uniqueId] = layer;
        }
        return layers;
    }

    /**
     * Get layers from the catalog queried by the given options
     *
     * @param {string[]} ids any amount of ids
     * @returns {Promise} promise returns an array of layers in the index format
     */
    async fetchLayersByIds(ids) {
        let query = '(uniqueId:(';
        for (let i = 0; i < ids.length; ++i) {
            query += '"' + ids[i] + '" ';
        }
        query += '))';

        const params = { query: query, hits: ids.length }
        return await this.fetchLayers(params);
    }

}