All files utilities.ts

100% Statements 28/28
95% Branches 19/20
100% Functions 1/1
100% Lines 28/28

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    1x 30x 30x 30x 90x 90x 7x 5x 7x 4x 90x 90x 6x 5x 6x 4x 90x 90x 13x 11x 13x 11x 90x 30x 30x 30x   30x 30x  
import type { Options } from "./types";
 
export function replacePathParams(path: string, params: Options["params"]) {
  const realPath = path
    .split("/")
    .map((segment) =>
      segment
        .replace(/^\[\[\.\.\.(.+)]]$/, (_, key) => {
          if (!params?.[key]) return "";
          const values = params[key];
          if (!Array.isArray(values)) throw new Error(`"${key}" must be an array`);
          return values.map(encodeURIComponent).join("/");
        })
        .replace(/^\[\.\.\.(.+)]$/, (_, key) => {
          if (!params?.[key]) throw new Error(`"${key}" is required`);
          const values = params[key];
          if (!Array.isArray(values)) throw new Error(`"${key}" must be an array`);
          return values.map(encodeURIComponent).join("/");
        })
        .replace(/^\[(.+)]$/, (_, key) => {
          if (!params?.[key]) throw new Error(`"${key}" is required`);
          const value = params[key];
          if (Array.isArray(value)) throw new Error(`"${key}" must be not an array`);
          return encodeURIComponent(String(value));
        }),
    )
    .filter((segment) => segment !== "")
    .join("/");
 
  return `/${realPath}`;
}