Files
Genarrative/src/services/runtimeRequest.ts
T

63 lines
1.5 KiB
TypeScript

import {
type ApiRetryOptions,
requestJson,
} from './apiClient';
import {
buildRuntimeGuestAuthOptions,
buildRuntimeGuestHeaders,
type RuntimeGuestRequestOptions,
} from './runtimeGuestAuth';
export type RuntimeJsonRequestParams = {
url: string;
method?: string;
jsonBody?: unknown;
headers?: Record<string, string>;
fallbackMessage: string;
retry?: ApiRetryOptions;
requestOptions?: RuntimeGuestRequestOptions;
};
export function buildRuntimeApiPath(
basePath: string,
...segments: string[]
) {
const normalizedBasePath = basePath.endsWith('/')
? basePath.slice(0, -1)
: basePath;
return [
normalizedBasePath,
...segments.map((segment) => encodeURIComponent(segment)),
].join('/');
}
export function requestRuntimeJson<T>(params: RuntimeJsonRequestParams) {
const {
fallbackMessage,
headers = {},
jsonBody,
method = 'GET',
requestOptions = {},
retry,
url,
} = params;
const hasJsonBody = jsonBody !== undefined;
const requestHeaders = buildRuntimeGuestHeaders(requestOptions, {
...(hasJsonBody ? { 'Content-Type': 'application/json' } : {}),
...headers,
});
const init: RequestInit = {
method,
...(Object.keys(requestHeaders).length > 0
? { headers: requestHeaders }
: {}),
...(hasJsonBody ? { body: JSON.stringify(jsonBody) } : {}),
};
const authOptions = buildRuntimeGuestAuthOptions(requestOptions);
return requestJson<T>(url, init, fallbackMessage, {
...(retry ? { retry } : {}),
...authOptions,
});
}