Files
stroy-bot-monorepo/src/webparts/stroyBot/services/http/spfxClients.ts
T
Тимур Городецкий 3128190b5c fix: retry AAD client creation after a failed token request
The rejected promise was cached, so a single network hiccup while
getting the Dataverse or API token broke every request to that resource
until the page was reloaded. Seen once in T-OBJ-11.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 10:07:07 +05:00

49 lines
2.0 KiB
TypeScript

import { WebPartContext } from '@microsoft/sp-webpart-base';
import { SPHttpClient, AadHttpClient } from '@microsoft/sp-http';
import { IHttpClient, IHttpRequest, IHttpResponse } from './IHttpClient';
// Адаптеры SPFx-клиентов к IHttpClient. Вся работа с авторизацией — здесь,
// остальной код о SPFx не знает.
export function createSharePointClient(context: WebPartContext): IHttpClient {
return {
fetch: (url: string, request: IHttpRequest = {}): Promise<IHttpResponse> =>
context.spHttpClient.fetch(url, SPHttpClient.configurations.v1, {
method: request.method ?? 'GET',
headers: request.headers,
body: request.body
})
};
}
/**
* Клиент к ресурсу под AAD (Dataverse или корпоративный API).
* AadHttpClient создаётся лениво и один раз — получение клиента запрашивает токен.
*/
export function createAadClient(context: WebPartContext, resource: string): IHttpClient {
let clientPromise: Promise<AadHttpClient> | undefined;
// Неудачную попытку не запоминаем: иначе одна сетевая осечка при получении токена
// ломала бы все запросы к этому ресурсу до перезагрузки страницы.
const getClient = (): Promise<AadHttpClient> => {
if (!clientPromise) {
clientPromise = context.aadHttpClientFactory.getClient(resource).catch((error: unknown) => {
clientPromise = undefined;
throw error;
});
}
return clientPromise;
};
return {
fetch: async (url: string, request: IHttpRequest = {}): Promise<IHttpResponse> => {
const client = await getClient();
return client.fetch(url, AadHttpClient.configurations.v1, {
method: request.method ?? 'GET',
headers: request.headers,
body: request.body
});
}
};
}