All files / packages/i18n/src/core/adapters/clients OfetchHttpClient.ts

100% Statements 11/11
100% Branches 6/6
100% Functions 4/4
100% Lines 11/11

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        5x   5x 9x   5x 9x             21x     18x             9x   9x 2x                 7x      
import { FetchError, type $Fetch } from "ofetch";
import { UpstreamError } from "#core/domain/errors";
import type { HttpClient, HttpResponse, RequestOptions } from "#core/ports/HttpClient";
 
const JSON_CONTENT_TYPE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json$/i;
 
const isJson = (contentType: string | null): boolean =>
    !contentType || JSON_CONTENT_TYPE.test(contentType.split(";")[0]!.trim());
 
const rethrowAsUpstreamError = (cause: unknown): never => {
    throw new UpstreamError(
        cause instanceof FetchError ? cause.response?.status : undefined,
        cause,
    );
};
 
export class OfetchHttpClient implements HttpClient {
    constructor(private readonly $fetch: $Fetch) {}
 
    public async get<T>(url: string, options?: RequestOptions): Promise<HttpResponse<T>> {
        const response = await this.$fetch
            .raw<T>(url, {
                headers: options?.headers,
                query: options?.query,
            })
            .catch(rethrowAsUpstreamError);
 
        const contentType = response.headers.get("content-type");
 
        if (!isJson(contentType)) {
            throw new UpstreamError(
                response.status,
                new Error(
                    `Expected JSON from ${url}, got ${contentType} (${response.status}): ` +
                        String(response._data).slice(0, 300),
                ),
            );
        }
 
        return { data: response._data as T, headers: response.headers };
    }
}