All files / router/src url.ts

100% Statements 24/24
100% Branches 14/14
100% Functions 1/1
100% Lines 24/24

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                                                    1x 40x   40x 17x 19x 19x 17x   40x 3x 3x   40x 23x   23x 31x 1x 31x 30x 30x 31x   23x 23x 23x   40x 40x  
/**
 * Constructs a URL string from a route path, parameters, and query parameters.
 *
 * This function replaces dynamic path segments (e.g., `:id`) with provided values
 * and appends a query string if query parameters are present. It handles both
 * single values and arrays for query parameters.
 *
 * @param path - The base route path (e.g., `/users/:id`)
 * @param params - Optional record of path parameters to replace dynamic segments
 * @param query - Optional record of query parameters to append to the URL
 * @returns The constructed URL string, ensuring it starts with a leading slash
 *
 * @example
 * ```ts
 * // Basic path replacement
 * createUrl('/users/:id', { id: '123' });
 * // Returns: '/users/123'
 *
 * // With query parameters
 * createUrl('/users/:id', { id: '123' }, { tab: 'profile', active: 'true' });
 * // Returns: '/users/123?tab=profile&active=true'
 *
 * // With array query parameters
 * createUrl('/search', {}, { tags: ['js', 'ts'] });
 * // Returns: '/search?tags=js&tags=ts'
 */
export function createUrl(path: string, params?: Record<string, unknown>, query?: Record<string, unknown>) {
  let url = path;
 
  if (params) {
    for (const [key, value] of Object.entries(params)) {
      url = url.replace(`:${key}`, String(value));
    }
  }
 
  if (url.endsWith('/')) {
    url = url.slice(0, -1);
  }
 
  if (query && Object.keys(query).length > 0) {
    const searchParams = new URLSearchParams();
 
    for (const [key, value] of Object.entries(query)) {
      if (Array.isArray(value)) {
        (value as string[]).forEach((item) => searchParams.append(key, String(item)));
      } else {
        searchParams.set(key, String(value));
      }
    }
 
    const queryString = searchParams.toString();
    url += (url.includes('?') ? '&' : '?') + queryString;
  }
 
  return url.startsWith('/') ? url : `/${url}`;
}