All files / src request.ts

88% Statements 22/25
90% Branches 9/10
75% Functions 3/4
90% Lines 18/20

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 552x                   2x           2x 1x       40x 40x 40x 40x   40x 40x           40x   78x     2x 2x       38x             2x 40x 38x    
import { HttpResponseError } from './model/Errors';
 
type RequestArgs = {
	endpoint: string;
	requestBody?: Record<string, unknown>;
	headers?: Record<string, string>;
};
 
type RequestOptions = RequestArgs & Omit<RequestInit, 'body' | 'headers'>;
 
let globalRequestOptions: Partial<RequestOptions> = {};
 
/**
 * An object containing any custom settings that you want to apply to the global fetch method.
 * @param options See possible options here: https://developer.mozilla.org/en-US/docs/Web/API/fetch#options
 */
export function setGlobalRequestOptions(options: Partial<RequestOptions>): void {
	globalRequestOptions = options;
}
 
async function _request({
	endpoint,
	requestBody,
	headers: requestHeaders,
	...options
}: RequestOptions): Promise<unknown> {
	const body = requestBody ? JSON.stringify(requestBody) : undefined;
	const headers = {
		...{ Accept: 'application/json, text/plain, */*' },
		...(body ? { 'Content-Type': 'application/json' } : undefined),
		...requestHeaders
	};
 
	const response = await fetch(endpoint, { body, headers, ...options });
 
	if (!response.ok) {
		// expecting: { error: '', code: 0 }
		// or: { detail: '' } (cashuBtc via pythonApi)
		const { error, detail } = await response.json().catch(() => ({ error: 'bad response' }));
		throw new HttpResponseError(error || detail || 'bad response', response.status);
	}
 
	try {
		return await response.json();
	} catch (err) {
		console.error('Failed to parse HTTP response', err);
		throw new HttpResponseError('bad response', response.status);
	}
}
 
export default async function request<T>(options: RequestOptions): Promise<T> {
	const data = await _request({ ...options, ...globalRequestOptions });
	return data as T;
}