domain/loaders/surface.loader.ts

domain/loaders/surface.loader.ts is a file in Bane's Lab Site. 33 lines of code and 7 definitions.

import type { SurfaceFigureName, SurfaceRecording } from "#types/surface.types";
import { SURFACE_UNAVAILABLE } from "#configuration/strings/report.strings";
import { isRecording } from "#core/predicates/surface.predicate";
import { reportFailure } from "#core/reporters/failure.reporter";
import { surfaceLocation } from "#core/assets/surface.asset";

const recordings = new Map<SurfaceFigureName, Promise<SurfaceRecording | null>>();

const fetchRecording = async function fetchRecording(figure: SurfaceFigureName): Promise<SurfaceRecording | null> {
    try {
        const response = await fetch(surfaceLocation(figure));
        const parsed: unknown = response.ok ? await response.json() : null;
        if (isRecording(parsed)) {
            return parsed;
        }
        reportFailure(SURFACE_UNAVAILABLE, figure);
    } catch (error) {
        reportFailure(SURFACE_UNAVAILABLE, error);
    }
    return null;
};

export const loadRecording = async function loadRecording(figure: SurfaceFigureName): Promise<SurfaceRecording | null> {
    const pending = recordings.get(figure);
    if (pending !== undefined) {
        return pending;
    }
    const loading = fetchRecording(figure).then((recording) => {
        if (recording === null) {
            recordings.delete(figure);
        }
        return recording;
    });
    recordings.set(figure, loading);
    return loading;
};