All files / frontend/manifest query.js

96.2% Statements 76/79
95.29% Branches 81/85
82.35% Functions 14/17
100% Lines 73/73

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 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                                                                                        6x 6x   6x 6x       6x 2x     2x 2x 2x 2x 3x 2x 2x 1x   2x                             10x 10x 5x 5x   5x   10x       10x     6x   6x     31x         33x 33x 33x 5x 5x 5x 5x 5x                 5x 1x     5x         5x 1x     28x 5x         5x 1x     5x         2x 1x     23x 23x 23x 23x     6x 6x 2x 2x 2x 2x 1x   1x   4x   27x               2x       2x             2x         2x         2x         6x           6x 26x 26x 21x 14x     7x   7x 7x        
/*
  Copyright (C) 2021 owner Roman Piontik R.Piontik@mail.ru
 
  Copyright (C) 2022 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
 
  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project
 
  https://dochub.info
 
  The use of this product or its derivatives for any purpose cannot be a secret.
 
 
  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.
 
  Maintainers:
      R.Piontik <r.piontik@mail.ru>
 
  Contributors:
      Rostislav Kabalin <kabalin2009@yandex.ru> - 2022
      R.Piontik <r.piontik@mail.ru> - 2023
*/
 
import jsonataDriver from '@global/jsonata/driver.mjs';
import queries from '@global/jsonata/queries.mjs';
import jsonataFunctions from '@global/jsonata/functions.mjs';
import env, {Plugins} from '@front/helpers/env';
import requests from '@front/helpers/requests';
import { PerformanceLogger } from '@global/logger/perf-logger.mjs';
import datasets from '@front/helpers/datasets';
import {getLogger, getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import {addPapiSettingUpdateCallbacks} from '@ide/papiLifeCycle';
import { unenvelopeDocument } from '@global/helpers/api/unenvelope.js';
 
const LOG_TAG = 'front-jsonata-helper';
const logger = getLoggerWithTag(LOG_TAG);
 
jsonataDriver.getDatasetDriver = () => datasets();
jsonataDriver.manifestSchema = () => window.Vuex?.state?.entities?.appliedSchema || {};
 
let pluginLogFunc;
 
if (env.isPlugin(Plugins.idea)) { // window.$PAPI.sendJsonataLog реализован только для jetbrains
    addPapiSettingUpdateCallbacks({
        funcName: 'change isJsonataLogFuncEnable',
        func: () => {
            const isJsonataLogFuncEnable = env.isJsonataLogFuncEnable;
            jsonataDriver.isJsonataLogFuncEnable = isJsonataLogFuncEnable;
            logger.debug(() => `change isJsonataLogFuncEnable = ${isJsonataLogFuncEnable}`);
            pluginLogFunc = (content, tag) => {
                if (isJsonataLogFuncEnable) {
                    let contentToSend = 'null or undefined';
                    if (content) {
                        contentToSend = JSON.stringify(content, null, 2);
                    }
                    window.$PAPI.sendJsonataLog({
                        level: 'info',
                        tag: tag ?? 'log-func-no-tag',
                        message: contentToSend
                    });
                }
            };
        }
    });
}
 
// Возвращает тело запроса в зависимости от платформы развертывания.
// В backend-режиме params временно едут в marker-URL (frontend-only),
// evaluate забирает их и кладёт в POST body — на HTTP query string не уходит.
function resolveJSONataRequest(ID, params) {
    let result = null;
    if (env.isBackendMode) {
        result = `backend://jsonata/${encodeURIComponent(ID)}`;
        params && (result += `?params=${encodeURIComponent(JSON.stringify(params))}`);
    } else {
        result = queries.makeQuery(queries.QUERIES[ID], params);
    }
    return result;
}
 
function parseSearchJson(value) {
    return value ? JSON.parse(value) : undefined;
}
 
const perfLogger = env.isPerfLoggerEnabled ? new PerformanceLogger(getLogger()) : null;
 
const queryDriver = {
    driver: jsonataDriver,
    expression(expression, self_, params, isTrace, funcs) {
        return {
            driver: this.driver,
            expOrigin: null,
            onError: null,
            async evaluate(context, def) {
                let result = null;
                try {
                    if (expression.startsWith('backend://')) {
                        const url = new URL(expression);
                        const query = decodeURIComponent((url.pathname || '/').slice(1));
                        const urlParams = parseSearchJson(url.searchParams.get('params'));
                        const urlSubject = parseSearchJson(url.searchParams.get('subject'));
                        const body = {
                            query,
                            params: (urlParams || params)
                                ? Object.assign({}, params || {}, urlParams || {})
                                : null,
                            subject: (urlSubject || self_)
                                ? Object.assign({}, self_ || {}, urlSubject || {})
                                : null
                        };
                        if (env.isEnvelopedRequests) {
                            body.envelope = true;
                        }
 
                        result = (await requests.request('backend://jsonata', null, {
                            method: 'POST',
                            data: body
                        })).data;
 
                        if (env.isEnvelopedRequests) {
                            result = unenvelopeDocument(result);
                        }
 
                    } else if (!context && env.isBackendMode) {
                        const body = {
                            query: expression,
                            params: params || null,
                            subject: self_ || null
                        };
                        if (env.isEnvelopedRequests) {
                            body.envelope = true;
                        }
 
                        result = (await requests.request('backend://jsonata', null, {
                            method: 'POST',
                            data: body
                        })).data;
 
                        if (env.isEnvelopedRequests) {
                            result = unenvelopeDocument(result);
                        }
                    } else {
                        funcs = funcs || {};
                        funcs.log = funcs.log || pluginLogFunc;
                        !this.expOrigin && (this.expOrigin = this.driver.expression(expression, self_, params, isTrace || env.isTraceJSONata, funcs));
                        result = await this.expOrigin.evaluate(context || window.Vuex.state.manifest || {});
                    }
                } catch (e) {
                    let message = null;
                    if (env.isBackendMode && e?.request?.response) {
                        const content = typeof e?.request?.response === 'object' ? e?.request?.response : JSON.parse(e?.request?.response);
                        message = content.message;
                        logger.error(() => message);
                        if (content.error) {
                            throw content.error;
                        } else {
                            throw e;
                        }
                    } else throw e;
                }
                return result ?? def;
            }
        };
    },
 
    // ********** ТЕХНОЛОГИИ ***********
    // Сбор информации об использованных технологиях
    collectTechnologies() {
        return resolveJSONataRequest(queries.IDS.TECHNOLOGIES);
    },
    // Карточка технологии
    summaryForTechnology(technology) {
        return resolveJSONataRequest(queries.IDS.TECHNOLOGY, { TECH_ID: technology });
    },
 
    // ********** СУЩНОСТИ ***********
 
    // Документы для сущности
    docsForSubject(entity) {
        return resolveJSONataRequest(queries.IDS.DOCUMENTS_FOR_ENTITY, { ENTITY: entity });
    },
 
    // Сводная JSONSchema по всем кастомным сущностям
    entitiesJSONSchema() {
        return resolveJSONataRequest(queries.IDS.JSONSCHEMA_ENTITIES);
    },
 
    // Сводная JSONSchema по всем кастомным сущностям
    getObject(id) {
        return resolveJSONataRequest(queries.IDS.GET_OBJECT, { OBJECT_ID: id });
    }
};
 
// Кэш для пользовательских функций
const cacheFunction = {
    moment: null,
    functions: null
};
 
// Регистрация пользовательских функций
jsonataDriver.customFunctions = () => {
    const state = window.Vuex?.state || {};
    if (!state.moment) return {};
    if (cacheFunction.moment && (cacheFunction.moment === state.moment))
        return cacheFunction.functions;
 
    // Реактивный манифест может содержать Proxy. Валидаторы остаются в обработчиках текущей версии манифеста.
    const result = (cacheFunction.functions = jsonataFunctions(() => queryDriver, state?.manifest?.functions || {}, perfLogger));
 
    cacheFunction.moment = state.moment;
    return result;
};
 
export default queryDriver;