All files define-routes.ts

100% Statements 12/12
100% Branches 8/8
100% Functions 2/2
100% Lines 10/10

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                                              12x 12x 12x 31x 31x 31x 71x 38x 31x   12x    
import { compileUrl } from './compile-url'
import type { Method, ParamValue, QueryValue, RouteDef, Routes, RoutesConfig } from './types'
 
type Params = Record<string, ParamValue>
type Query = Record<string, QueryValue>
 
interface CallArgs {
  params?: Params
  /** params shorthand */
  p?: Params
  query?: Query
  /** query shorthand */
  q?: Query
  hash?: ParamValue
  /** hash shorthand */
  h?: ParamValue
}
 
type UrlFn = (args?: CallArgs) => string
 
export function defineRoutes<R extends Record<string, RouteDef>, const B extends string | undefined = undefined>(
  config: RoutesConfig<R, B>,
): Routes<R, NoInfer<B>> {
  const result: Record<string, unknown> = {}
  const routes: Record<string, RouteDef> = config.routes
  for (const path in routes) {
    const def = routes[path]
    const url = compileUrl(config.baseUrl, path)
    const methods = def.kind === 'route' ? def.methods : { get: def }
    const fn: UrlFn & { [M in Method]?: UrlFn } = (a) => url(a?.params ?? a?.p, a?.query ?? a?.q, a?.hash ?? a?.h)
    for (const method in methods) fn[method as Method] = fn
    result[path] = fn
  }
  return result as Routes<R, B>
}