All files / apps/huella-legal/layers/forms/app/composables useFormPost.ts

100% Statements 33/33
96.15% Branches 25/26
100% Functions 5/5
100% Lines 31/31

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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94                              10x 2x   2x 15x 13x         12x       2x               10x               26x 26x 26x   26x 13x   13x   13x 2x 2x     11x 13x       26x 22x   21x 21x 21x   21x 21x 20x   20x         8x   13x       26x              
import type { Challenge } from "../types/Challenge";
import type { FormError } from "@nuxt/ui";
 
export type FormPostStatus = "idle" | "submitting" | "success" | "invalid" | "error";
 
interface Rejection<Issue extends FormError> {
    statusCode?: number;
    data?: { data?: Issue[] };
}
 
interface Options<Failure extends string> {
    failures?: Partial<Record<number, Failure>>;
    multipart?: boolean;
}
 
const toFormData = (fields: Record<string, unknown>): FormData => {
    const data = new FormData();
 
    for (const [name, value] of Object.entries(fields)) {
        if (value instanceof Blob) data.append(name, value);
        else if (
            typeof value === "string" ||
            typeof value === "number" ||
            typeof value === "boolean"
        ) {
            data.append(name, String(value));
        }
    }
 
    return data;
};
 
/**
 * One form's state machine: idle → submitting → success, invalid or error. A `422` leaves the
 * server's issue codes in `errors`; any other refusal leaves its `failures` entry in `failure`.
 * `multipart` posts the fields as `FormData`, which a file needs.
 */
export const useFormPost = <
    Request extends FormRequest,
    Issue extends FormError,
    Failure extends string = never,
>(
    endpoint: string,
    { failures = {}, multipart = false }: Options<Failure> = {},
) => {
    const status = ref<FormPostStatus>("idle");
    const errors = ref<Issue[]>([]);
    const failure = ref<Failure | "unavailable">();
 
    const fail = (error: unknown) => {
        const { statusCode, data } = (error ?? {}) as Rejection<Issue>;
 
        errors.value = statusCode === 422 ? (data?.data ?? []) : [];
 
        if (errors.value.length) {
            status.value = "invalid";
            return;
        }
 
        failure.value = failures[statusCode ?? 0] ?? "unavailable";
        status.value = "error";
    };
 
    /** Sends the fields once the form's challenge yields a token. */
    const send = async (fields: Omit<Request, "token">, challenge: Challenge) => {
        if (status.value === "submitting") return;
 
        status.value = "submitting";
        errors.value = [];
        failure.value = undefined;
 
        try {
            await challenge((token) => {
                const body = { ...fields, token };
 
                return $fetch(endpoint, {
                    method: "POST",
                    body: multipart ? toFormData(body) : body,
                });
            });
            status.value = "success";
        } catch (error) {
            fail(error);
        }
    };
 
    return {
        status: readonly(status),
        errors: readonly(errors),
        failure: readonly(failure),
        send,
    };
};