All files / js/wayfinder index.ts

0% Statements 0/52
0% Branches 0/41
0% Functions 0/9
0% Lines 0/50

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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146                                                                                                                                                                                                                                                                                                   
export type QueryParams = Record<
    string,
    | string
    | number
    | boolean
    | string[]
    | null
    | undefined
    | Record<string, string | number | boolean>
>;
 
type Method = "get" | "post" | "put" | "delete" | "patch" | "head" | "options";
 
let urlDefaults: Record<string, unknown> = {};
 
export type RouteDefinition<TMethod extends Method | Method[]> = {
    url: string;
} & (TMethod extends Method[] ? { methods: TMethod } : { method: TMethod });
 
export type RouteFormDefinition<TMethod extends Method> = {
    action: string;
    method: TMethod;
};
 
export type RouteQueryOptions = {
    query?: QueryParams;
    mergeQuery?: QueryParams;
};
 
export const queryParams = (options?: RouteQueryOptions) => {
    if (!options || (!options.query && !options.mergeQuery)) {
        return "";
    }
 
    const query = options.query ?? options.mergeQuery;
    const includeExisting = options.mergeQuery !== undefined;
 
    const getValue = (value: string | number | boolean) => {
        if (value === true) {
            return "1";
        }
 
        if (value === false) {
            return "0";
        }
 
        return value.toString();
    };
 
    const params = new URLSearchParams(
        includeExisting && typeof window !== "undefined"
            ? window.location.search
            : "",
    );
 
    for (const key in query) {
        if (query[key] === undefined || query[key] === null) {
            params.delete(key);
            continue;
        }
 
        if (Array.isArray(query[key])) {
            if (params.has(`${key}[]`)) {
                params.delete(`${key}[]`);
            }
 
            query[key].forEach((value) => {
                params.append(`${key}[]`, value.toString());
            });
        } else if (typeof query[key] === "object") {
            params.forEach((_, paramKey) => {
                if (paramKey.startsWith(`${key}[`)) {
                    params.delete(paramKey);
                }
            });
 
            for (const subKey in query[key]) {
                if (typeof query[key][subKey] === "undefined") {
                    continue;
                }
 
                if (
                    ["string", "number", "boolean"].includes(
                        typeof query[key][subKey],
                    )
                ) {
                    params.set(
                        `${key}[${subKey}]`,
                        getValue(query[key][subKey]),
                    );
                }
            }
        } else {
            params.set(key, getValue(query[key]));
        }
    }
 
    const str = params.toString();
 
    return str.length > 0 ? `?${str}` : "";
};
 
export const setUrlDefaults = (params: Record<string, unknown>) => {
    urlDefaults = params;
};
 
export const addUrlDefault = (
    key: string,
    value: string | number | boolean,
) => {
    urlDefaults[key] = value;
};
 
export const applyUrlDefaults = <T extends Record<string, unknown> | undefined>(
    existing: T,
): T => {
    const existingParams = { ...(existing ?? ({} as Record<string, unknown>)) };
 
    for (const key in urlDefaults) {
        if (
            existingParams[key] === undefined &&
            urlDefaults[key] !== undefined
        ) {
            (existingParams as Record<string, unknown>)[key] = urlDefaults[key];
        }
    }
 
    return existingParams as T;
};
 
export const validateParameters = (
    args: Record<string, unknown> | undefined,
    optional: string[],
) => {
    const missing = optional.filter((key) => !args?.[key]);
    const expectedMissing = optional.slice(missing.length * -1);
 
    for (let i = 0; i < missing.length; i++) {
        if (missing[i] !== expectedMissing[i]) {
            throw Error(
                "Unexpected optional parameters missing. Unable to generate a URL.",
            );
        }
    }
};