All files / global/search search-data.mjs

92.85% Statements 26/28
93.33% Branches 14/15
71.42% Functions 5/7
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      6x 6x                       35x 2x 2x   33x 33x 10x 10x   23x                 28x 28x   28x               33x 5x   28x   28x 16x 14x   12x   26x 26x               14x 14x 21x   13x      
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
  http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import { getSearchEntityConfig } from './search-config.mjs';
import { getLoggerWithTag } from '@global/logger/v2/logger.mjs';
 
const LOG_TAG = 'search-data';
const logger = getLoggerWithTag(LOG_TAG);
 
/**
 * Извлекает map объектов сущности из озера или результата датасета.
 * Датасет возвращает структуру, зеркалирующую озеро: { [entityId]: { objectKey: objectData } }.
 * Если срез отсутствует или пуст — возвращает {} (поиск по сущности даст 0 результатов).
 *
 * @param {object} source - manifest или результат releaseData
 * @param {string} entityId
 * @returns {Record<string, object>}
 */
export function extractEntityObjects(source, entityId) {
    if (!source || typeof source !== 'object') {
        logger.debug(() => `Entity ${entityId}: data source is empty, using empty object map`);
        return {};
    }
    const slice = source[entityId];
    if (!slice || typeof slice !== 'object' || Array.isArray(slice)) {
        logger.debug(() => `Entity ${entityId}: slice missing or invalid in source, using empty object map`);
        return {};
    }
    return slice;
}
 
export class SearchDataProvider {
    /**
     * @param {object} manifest
     * @param {(datasetId: string) => Promise<object>} loadDataset
     */
    constructor(manifest, loadDataset) {
        this.manifest = manifest;
        this.loadDataset = loadDataset;
        /** @type {Map<string, Record<string, object>>} */
        this.cache = new Map();
    }
 
    /**
     * @param {string} entityId
     * @returns {Promise<Record<string, object>>}
     */
    async getEntityData(entityId) {
        if (this.cache.has(entityId)) {
            return this.cache.get(entityId);
        }
        const config = getSearchEntityConfig(this.manifest, entityId);
        let data;
        if (config?.datasetId) {
            const loaded = await this.loadDataset(config.datasetId);
            data = extractEntityObjects(loaded ?? {}, entityId);
        } else {
            data = extractEntityObjects(this.manifest, entityId);
        }
        this.cache.set(entityId, data);
        return data;
    }
 
    /**
     * @param {string[]} entityIds
     * @returns {Promise<Record<string, Record<string, object>>>}
     */
    async getEntityDataMap(entityIds) {
        const uniqueIds = [...new Set(entityIds.filter(Boolean))];
        const entries = await Promise.all(
            uniqueIds.map(async(entityId) => [entityId, await this.getEntityData(entityId)])
        );
        return Object.fromEntries(entries);
    }
}