All files / packages/content/src/core/ports ContentProvider.ts

100% Statements 16/16
100% Branches 9/9
100% Functions 5/5
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                                      74x   74x 74x   74x               20x   16x 11x       3x   3x 2x       60x       74x         74x          
import type {
    Entry,
    EntryQuery,
    EntryResource,
    Page,
    Query,
    Term,
    TermResource,
} from "#core/domain/content";
import { MisconfiguredVendorError, NotFoundError } from "#core/domain/errors";
import type { Vendor } from "#core/domain/vendor";
import type { HttpClient } from "./HttpClient";
 
abstract class ContentProvider<T extends object = object> implements Vendor<T> {
    readonly baseURL: string;
    readonly options: T;
 
    constructor(
        { baseURL, options = {} as T }: Omit<Vendor<T>, "options"> & { options?: T },
        protected readonly http: HttpClient,
    ) {
        this.baseURL = baseURL;
        this.options = options;
 
        this.assertConfigured();
    }
 
    public abstract listEntries(resource: EntryResource, query?: EntryQuery): Promise<Page<Entry>>;
 
    public abstract listTerms(resource: TermResource, query?: Query): Promise<Page<Term>>;
 
    public async getEntry(resource: EntryResource, slug: string): Promise<Entry> {
        const { items } = await this.listEntries(resource, { slug, perPage: 1 });
 
        if (!items[0]) throw new NotFoundError(resource, slug);
        return items[0];
    }
 
    public async getTerm(resource: TermResource, slug: string): Promise<Term> {
        const { items } = await this.listTerms(resource, { slug, perPage: 1 });
 
        if (!items[0]) throw new NotFoundError(resource, slug);
        return items[0];
    }
 
    protected configProblems(): string[] {
        return [];
    }
 
    private assertConfigured(): void {
        const problems = [
            !URL.canParse(this.baseURL) ? "baseURL is not an absolute URL" : "",
            ...this.configProblems(),
        ].filter(Boolean);
 
        if (problems.length) throw new MisconfiguredVendorError(this.constructor.name, problems);
    }
}
 
export default ContentProvider;