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

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

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        5x   5x 44x   5x 13x 10x     3x       58x     57x             44x   44x 4x                 40x      
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 => {
    if (cause instanceof FetchError) {
        throw new UpstreamError(cause.response?.status, cause, cause.data);
    }
 
    throw new UpstreamError(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 };
    }
}