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 | 3x 22x 22x 1x 11x 3x 8x 13x 13x 13x 26x 26x 19x 28x 28x 28x 38x 38x 10x 10x 23x 28x 28x 28x 28x 12x 1x 1x 8x 8x 17x 21x 1x 8x 1x 9x 7x 7x 7x 7x 7x 7x 3x 1x 4x 7x 5x 3x 4x | /*
Copyright (C) 2023 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 {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
const logger = getLoggerWithTag('BaseEntities');
// Обрабатывает кастомные сущности
export class BaseEntities {
#appliedSchema = null;
#manifest = null;
// Подключает мастер-схему для подсказок и валидации метамодели
getMasterSchema() {
throw new Error('Method getMasterSchema is not implemented');
}
// Устанавливает манифест, по которому будет сгенерирована схема при необходимости
setManifest(manifest) {
this.#manifest = manifest;
}
// Генерирует список доступных типов документов
// по-умолчанию, ограничением является просто строка
makeDocTypesEnum() {
return {
'$doc-types': {
type: 'string'
}
};
}
// Генерирует схему DataSet
makeDataSetSchema(manifest) {
return {
$dataset: {
type: 'string',
enum: Object.keys(manifest.datasets || {})
}
};
}
// Генерируем схемы связей
makeSubjectsRelationsSchema(manifest) {
try {
const rels = {};
for (const entityId in manifest.entities || {}) {
const objects = manifest.entities[entityId].objects;
// Если сущность не публикует субъекты, то игнорируем ее
if (!objects) continue;
// Генерируем схемы связей с объектами
for (const subjectId in objects) {
const route = (objects[subjectId].route || '/').split('/');
let location = manifest[entityId] || {};
for (let i = 1; i < route.length; i++) {
let pice = route[i];
// если pice указывает на плейсхолдер inner и он не последний,
// тогда ищем следующий за ним атрибут во всех сущностях, отобранных к этому шагу
if (pice === '{inner}' && i < route.length - 1) {
i++;
pice = route[i];
location = Object.assign({}, ...Object.values(location).map(el => el[pice]));
} else { // иначе просто переходим вглубь объекта
pice?.length && (location = location[route[i]] || {});
}
}
const objId = `${entityId}.${subjectId}`;
const locations = Object.keys(location);
rels[objId] = {
type: 'string',
minLength: 1,
enum: locations.length > 0 ? locations : undefined
};
}
}
return rels;
} catch (e) {
logger.error(() => `Error of building of relations enumeration! ${e.message}`, e);
return {};
}
}
// Генерирует перечисления для подсказок
makeDefsEnum($defs, $rels) {
let items = [];
try {
items = Object.keys($defs).map((item) => `"#/$defs/${item}"`);
Object.keys($rels).map((item) => items.push(`"#/$rels/${item}"`));
} catch (e) {
logger.error(() => `Error of building of definitions enumeration! ${e.message}`, e);
}
return {
'$defs': {
type: 'string',
enum: items
}
};
}
async queryEntitiesJSONSchema() {
throw new Error('Method queryEntitiesJSONSchema is not implemented');
}
// загрузка схемы
async loadSchema() {
const queryResult = await this.queryEntitiesJSONSchema(this.#manifest);
const master = this.getMasterSchema();
const $defs = {
...master.$defs,
...queryResult.$defs,
...this.makeDataSetSchema(this.#manifest)
};
const $rels = this.makeSubjectsRelationsSchema(this.#manifest || {});
// Превращаем схему в строку для передачи в плагин
const schema = {
...queryResult,
properties: {
...master.$entities,
...queryResult.properties
},
$defs: {
...$defs,
...this.makeDefsEnum($defs, $rels),
...this.makeDocTypesEnum()
},
// Добавляем схемы связей с субъектами сущностей
$rels
};
logger.info(() => 'schema created');
return schema;
}
// Пересоздаёт схему по установленному манифесту
// Но только в случае, что схема уже создавалась (т.е. схемой уже хотя бы раз пользовались)
async reloadSchema() {
if (this.#appliedSchema !== null && this.#manifest !== null) {
this.#appliedSchema = await this.loadSchema();
}
}
updateSchema(schema) {
this.#appliedSchema = schema;
}
// Синхронный доступ к уже посчитанной схеме.
// JSONata функция $manifestschema() дёргает это на каждый вызов.
get appliedSchema() {
return this.#appliedSchema;
}
// Возвращает схему (создаёт, если ещё не создавалась и известен манифест, по которому создавать)
async getSchema() {
if (this.#appliedSchema === null && this.#manifest !== null) {
this.#appliedSchema = await this.loadSchema();
}
return this.#appliedSchema;
}
}
|