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 | 3x 51x 51x 55x 55x 16x 17x 17x 24x 24x 43x 43x 43x 43x 43x 43x 43x 43x 8x 8x 8x 45x 1x 44x 43x 14x 29x 34x 22x 11x 7x | /*
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 env from '@front/helpers/env';
import { sendRequest } from '@front/helpers/backend.api.helper.js';
import { traceIdHeader } from '@front/helpers/tracing';
import type {
ApiErrorBody,
DownloadedFile,
FileloaderClientError,
FileloaderError,
FileloaderResult
} from './fileloader2.types';
// HTTP-клиент fileloader2 для браузера. В плагине запросы делает сам плагин (см. fileloader2.api.ts)
const FILES_PATH = '/api/v1/files';
// Адрес читается при каждом запросе: s3CloudUrl приходит с бэкенда (setBackendEnv) или из настроек плагина после загрузки модуля
function filesUrl(): string {
const baseUrl = String(env.s3CloudUrl || '').trim().replace(/\/+$/, '');
return baseUrl ? `${baseUrl}${FILES_PATH}` : '';
}
/**
* Разбор JSON без исключения
* @param text - текст
* @returns значение или undefined, если текст не JSON
*/
export function safeJsonParse(text: string): unknown {
try {
return JSON.parse(text);
} catch (e) {
return undefined;
}
}
/**
* Адрес файла в fileloader2: {s3CloudUrl}/api/v1/files/{id}
* @param fileId - id файла, формат не проверяется: это делает fileloader2
* @returns абсолютный адрес или пустая строка, если s3CloudUrl не задан
*/
export function fileloaderFileUrl(fileId: string): string {
const url = filesUrl();
return url ? `${url}/${encodeURIComponent(String(fileId ?? ''))}` : '';
}
// "not set" fileloader2 пишет, когда трассировки нет: такой traceId ничего не даёт
function parseTraceId(traceId: unknown): string | undefined {
const value = typeof traceId === 'string' ? traceId.trim() : '';
return value && value !== 'not set' ? value : undefined;
}
/**
* Ошибка ответа fileloader2. Тело разбирается как ApiError {status, error, message, traceId}
* @param statusCode - HTTP-статус ответа
* @param body - тело ответа: текст или уже разобранный объект (ответ плагина)
*/
export function toFileloaderError(statusCode: unknown, body: unknown): FileloaderError {
const status = Number(statusCode) || 0;
const payload = (typeof body === 'string' ? safeJsonParse(body) : body) as ApiErrorBody | null | undefined;
const isApiError = !!payload && typeof payload === 'object'
&& typeof payload.message === 'string' && !!payload.message.trim();
const error = new Error(isApiError ? payload.message as string : `HTTP ${status}`) as FileloaderError;
error.status = status;
error.apiError = isApiError;
error.traceId = isApiError ? parseTraceId(payload.traceId) : undefined;
return error;
}
/**
* Ошибка работы с fileloader2, обнаруженная на фронте (например, ответ без имени файла)
* @param message - текст для пользователя
*/
export function toFileloaderClientError(message: string): FileloaderClientError {
const error = new Error(message) as FileloaderClientError;
error.clientError = true;
return error;
}
// Параметры запроса к fileloader2: заголовки ставит request
interface RequestOptions {
method: 'GET' | 'POST';
body?: FormData;
}
async function request(url: string, options: RequestOptions, traceId: string): Promise<Response> {
if (!url) {
throw toFileloaderError(0, '');
}
// rquid, а для хоста бэкенда orgCtx и Bearer добавляет sendRequest
const response: Response = await sendRequest(url, { ...options, headers: traceIdHeader(traceId) });
if (!response.ok) {
throw toFileloaderError(response.status, await response.text().catch(() => ''));
}
return response;
}
/**
* Загрузка файлов. Content-Type с границей multipart ставит сам браузер
* @param formData - части с именем files
* @param traceId - id действия пользователя (createTraceId)
* @returns статус и тело ответа текстом, как в ответе плагина
*/
export async function fileloaderUpload(formData: FormData, traceId: string): Promise<FileloaderResult> {
const response = await request(filesUrl(), { method: 'POST', body: formData }, traceId);
return { statusCode: response.status, data: await response.text() };
}
/**
* Скачивание файла
* @param fileId - id файла
* @param traceId - id действия пользователя (createTraceId)
*/
export async function fileloaderDownload(fileId: string, traceId: string): Promise<DownloadedFile> {
const response = await request(fileloaderFileUrl(fileId), { method: 'GET' }, traceId);
return {
headers: Object.fromEntries(response.headers.entries()),
blob: await response.blob()
};
}
|