All files / global/datasets driver.mjs

97.59% Statements 81/83
95.91% Branches 47/49
100% Functions 25/25
97.46% Lines 77/79

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                                                                                            1x             1x                 1x                 86x 86x 86x 86x   8x 8x   51x 51x 51x 49x   51x   3x 2x     2x 2x 2x 2x     3x   9x   5x 5x 5x 5x     9x   1x 2x   1x   1x 1x     1x         1x 1x   12x 12x 12x 12x 4x 4x     8x 8x 1x   8x   12x   1x       16x 16x   86x                 77x 77x 44x 43x 1x   77x 48x 6x 2x 1x 1x 4x 2x 2x 2x 3x   2x 2x   1x   2x 42x 29x                     4x 4x   3x 3x   3x        
/*
  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:
      R.Piontik <r.piontik@mail.ru> - 2023
*/
 
import { Parser } from '../../global/manifest/parser3/index.mjs';
import source from './source.mjs';
 
export default {
	// Метод получения объекта данных по пути в структуре
	// Путь имеет вид "/foo/foo/0/foo"
	// Возвращает структуру:
	//	{
	//		context - данные, по которым необходимо выполнять запросы
	//		subject - объект данных
	//		baseURI	- URI расположения исходников кода для разрешения относительных путей
	//  }
	// eslint-disable-next-line no-unused-vars
	pathResolver(path) {
		throw 'pathResolver is not released for backend yet :(';
	},
 
	// Драйвер доступа к данным через JSONata
	// Должен быть реализован
	jsonataDriver: {
		expression() {
			throw 'jsonataDriver is not implemented in the dataset module :(';
		}
	},
	traceJsonata: false,
	// Логер расширенного логирования
	performanceLogger: null,
	// Драйвер запросов
	// eslint-disable-next-line no-unused-vars
	request(url, baseURI) {
		throw 'request driver is not implemented in the dataset module :(';
	},
	// Парсит поле данных в любом объекте
	//  context 	- Контекст данных для выполнения запросов
	//  data 		- данные требующие парсинга (запрос / структура / идентификатор dataset)
	//	subject 	- объект - владелец
	//  params 		- параметры передающиеся в запрос
	//  baseURI		- URI от которого будут строиться относительные пути
	parseSource(context, data, subject, params, baseURI, trace, datasetsWithError) {
		let logger = null;
		return new Promise((resolve, reject) => {
			const sourceType = source.type(data, subject);
			switch(sourceType) {
				case 'data-object':
					resolve(JSON.parse(JSON.stringify(data)));
					break;
				case 'jsonata-query': {
					const exp = this.jsonataDriver.expression(data, subject, params, trace ?? this.traceJsonata);
					exp.onError = reject;
					exp.evaluate(context)
						.then((result) => resolve(result))
						.catch(reject);
				} break;
				case 'jsonata-file': {
					this.request(data, baseURI).then((response) => {
						const query = typeof response.data === 'string'
							? response.data
							: JSON.stringify(response.data);
						const exp = this.jsonataDriver.expression(`(${query})`, params);
						exp.onError = reject;
						exp.evaluate(context)
							.then((result) => resolve(result))
							.catch(reject);
					}).catch(reject);
				} break;
				case 'data-file': {
					this.request(data, baseURI)
						.then((response) => {
							const params = [context, response.data];
							params[6] = datasetsWithError;
							this.parseSource(...params)
								.then((result) => resolve(result))
								.catch(reject);
						}).catch(reject);
				} break;
				case 'data-manifest': {
					const parser = new Parser({strictMode: true});
					parser.onPullSource = (uri, baseURI) => this.request(uri, baseURI);
 
					parser.import(data, baseURI)
						.then(() => {
							parser.build();
							resolve(parser.manifest);
						}).catch(reject);
 
				} break;
				case 'resource': {
					reject(`Тип данных 'resource' не реализован  [${data}]`);
				} break;
				case 'resource-inline':
					resolve(JSON.parse(decodeURIComponent(data.slice(7))));
					break;
				case 'id': {
					logger = this.performanceLogger?.getDatasetLogger(data);
					logger?.setStart();
					const dataSet = this.pathResolver(`/datasets/${data}`);
					if (dataSet && dataSet.subject) {
						this.getData(context, dataSet.subject, params, dataSet.baseURI, datasetsWithError)
							.then((data) => resolve(data))
							.catch(reject);
					} else {
						let errorMessage = `Не найден источник данных [${data}]`;
						if (subject?._id && subject._id !== 'undefined' && subject._id !== 'null') {
							errorMessage += ` для расчета [${subject._id}]`;
						}
						reject(errorMessage);
					}
				} break;
				default:
					reject(`Ошибка источника данных [${sourceType}: ${data}]`);
			}
		})
		.catch((error) => {
			if(datasetsWithError && !datasetsWithError?.[data]) datasetsWithError[data] = {uri: baseURI, error};
			throw error;
		})
		.finally(() => logger?.setEnd());
	},
 
	// Возвращает данные по субъекту
	//  context - данные для запроса
	//  subject - субъект данных
	//  params 	- параметры передающиеся в запрос
	//  baseURI	- URI от которого будут строиться относительные пути
	getData(context, subject, params, baseURI, datasetsWithError = {}) {
		return new Promise((resolve, reject) => {
			const exec = (origin) => {
				this.parseSource(origin, subject.source || (subject.data /* depricated */), subject, params, baseURI)
					.then((data) => resolve(data))
					.catch((e) => reject(e));
			};
			if (subject.source || (subject.data /* depricated */)) {
				if (subject.origin) {
					if (typeof subject.origin === 'string') {
						this.parseSource(context, subject.origin, subject, params, baseURI, datasetsWithError)
							.then((data) => exec(data))
							.catch((e) => reject(e));
					} else if ((typeof subject.origin === 'object') && !Array.isArray(subject.origin)) {
						let counter = Object.keys(subject.origin).length;
						const data = {};
						for (const key in subject.origin) {
							this.parseSource(context, subject.origin[key], subject, params, baseURI, datasetsWithError)
								.then((content) => {
									data[key] = content;
									if (!--counter) exec(data);
								})
								.catch((e) => reject(e));
						}
					} else reject(`Ошибка данных [${subject.source}]`);
				} else exec(context);
			} else resolve(null); // Нет данных
		});
	},
 
	// [path] = {
	//		origin - Необязательно. Ссылка на оригинальный DataSet / JSONata запрос / Ссылка на файл данных / константная структура
	//		source - идентификатор DataSet / JSONata запрос / Ссылка на файл данных / константная структура
	// }
	// Сам объект передается в запрос в переменной $self
	// $self._id автоматически генерируемое поле содержащее последний сегмент path
	async releaseData(path, params) {
		const meta = await this.pathResolver(path);
		if (!meta) throw `Error of access to object via path [${path}]`;
 
		const subject = Object.assign({_id: path.split('/').pop()}, meta.subject || {});
		const baseURI = meta.baseURI || '/';
 
		return await this.getData(meta.context, subject, params, baseURI);
	}
};