All files / frontend/helpers backend.api.helper.js

95.55% Statements 43/45
92.85% Branches 39/42
71.42% Functions 5/7
100% Lines 43/43

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                                              82x                 82x 134x 134x   134x 134x 129x 129x 108x     21x       129x 129x 29x     134x                     82x 134x 134x 134x     130x 11x 11x 7x         7x 7x 3x       130x                       82x 84x 84x 81x 81x   81x 12x   69x   12x   3x                       82x 77x     82x 12x 5x 4x   1x        
/*
  Copyright (C) 2025 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 {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
import { v4 as uuidv4 } from 'uuid';
import { HttpHeaders } from '@global/helpers/httpHeaders.mjs';
import {extreactOrgCtxFromWindow, isUriHostEqualBackendHost} from '@front/helpers/orgCtxTools.js';
import userStore from '@front/store/userStore.js';
 
const logger = getLoggerWithTag('f/h/backend.api.helper');
 
/**
 * Проставляет заголовки запроса к сервисам SEAF: id запроса, а для хоста бэкенда ещё OIDC Bearer и orgCtx
 * @param url - адрес запроса
 * @param headers - заголовки запроса, дополняются на месте; id запроса генерируется, если его не передали
 * @param tokenOptions - опции получения токена для запроса к backend (userStore.getAccessToken)
 * @returns {Promise<string|null>} - токен, с которым уходит запрос к бэкенду, или null
 */
const applyRequestHeaders = async(url, headers, tokenOptions) => {
    Eif (!headers[HttpHeaders.REQUEST_ID]) {
        headers[HttpHeaders.REQUEST_ID] = uuidv4();
    }
    let accessToken = null;
    if (env.backendURL && isUriHostEqualBackendHost(url)) {
        accessToken = await userStore.getAccessToken(tokenOptions);
        if (accessToken) {
            headers.Authorization = `Bearer ${accessToken}`;
        } else {
            // заголовки вызывающего могли нести старый токен: запрос без токена уходит без Authorization
            delete headers.Authorization;
        }
        // Контекст организации — после токена: после старта без токена userStore с первым токеном
        // загружает права и ставит контекст в адрес страницы, а запрос ждёт этого
        const orgCtx = extreactOrgCtxFromWindow();
        if (orgCtx) {
            headers[HttpHeaders.X_SFA_ORGCTX] = orgCtx;
        }
    }
    return accessToken;
};
 
/**
 * Отправка запроса с заголовками SEAF (см. applyRequestHeaders) без разбора ответа и без перехвата ошибок.
 * На 401 от бэкенда — не больше одного обновления токена и один повтор (кроме фоновых запросов)
 * @param url - адрес запроса
 * @param options - опции fetch, не меняются
 * @param tokenOptions - опции получения токена для запроса к backend (userStore.getAccessToken)
 * @returns {Promise<Response>} - ответ fetch как есть
 */
export const sendRequest = async(url, options = {}, tokenOptions) => {
    const headers = {...(options.headers || {})};
    const accessToken = await applyRequestHeaders(url, headers, tokenOptions);
    let response = await fetch(url, {...options, headers});
    // Бэк не принял запрос: не больше одного обновления на токен и один повтор; 401 на повтор — отказ по правам.
    // Фоновый запрос (background) на 401 токен не обновляет, не повторяется и на вход не уводит
    if (response.status === 401 && !tokenOptions?.background && env.backendURL && isUriHostEqualBackendHost(url)) {
        const retryToken = await userStore.handleUnauthorized(accessToken);
        if (retryToken) {
            const retryHeaders = {
                ...headers,
                Authorization: `Bearer ${retryToken}`,
                [HttpHeaders.REQUEST_ID]: uuidv4()
            };
            response = await fetch(url, {...options, headers: retryHeaders});
            if (response.status === 401) {
                await userStore.handleUnauthorized(retryToken, {retried: true});
            }
        }
    }
    return response;
};
 
/**
 * Отправка запроса на любой внешний ресурс
 * в отличие от requests.request('backend://...') не подставляет /core/storage и дает возможность обращаться к любому адресу
 * @param url - адрес куда надо отправить запрос
 * @param options - опции запроса передаются напрямую в fetch (тип запроса, заголовки и прочее)
 * @param statusMapping - мапинг статуса ответа/ошибки
 * @param tokenOptions - опции получения токена для запроса к backend (userStore.getAccessToken)
 * @returns {Promise<undefined|any>}
 */
export const handledRequest = async(url, options = {}, statusMapping, tokenOptions) => {
    try {
        const request = await sendRequest(url, options, tokenOptions);
        const text = !request.ok ? await request.text() : '';
        const response = request.ok ? await request.json() : text ? JSON.parse(text) : undefined;
 
        if (!request.ok) {
            handleError(response, request.status, statusMapping);
        } else {
            return response;
        }
        return undefined;
    } catch (e) {
        return undefined;
    }
};
 
/**
 * Запрос к backend просто обертка над handledRequest, чтобы не передавать каждый раз env.backendURL
 * @param relativeUrl - относительный адрес сервиса на backend (относительно базового url env.backendURL)
 * @param options - смотри handledRequest
 * @param statusMapping - смотри handledRequest
 * @param tokenOptions - смотри handledRequest
 * @returns {Promise<*|undefined>}
 */
export const requestToBackend = async(relativeUrl, options = {}, statusMapping = null, tokenOptions) => {
    return handledRequest(env.backendURL + relativeUrl, options, statusMapping, tokenOptions);
};
 
const handleError = (error, code, statusMapping) => {
    if (error) {
        if (code === 500 || code === 409) {
            logger.error(() => `handleError status 500/409: ${statusMapping?.[500] ?? error.message}`);
        } else {
            logger.error(() => `handleError error: ${error?.message}`);
        }
    }
};