All files / packages / shared/src endpoint.ts

100% Statements 5/5
100% Branches 3/3
100% Functions 2/2
100% Lines 4/4

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                                                                6x 7x 7x   5x      
import type { ZodType, input, output } from 'zod'
 
// One HTTP endpoint, shared by the API (registers it), the web (calls it) and the OpenAPI doc.
export interface Endpoint {
  method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
  /** Hono style: `/api/sessions/:id`. */
  path: string
  params?: ZodType
  query?: ZodType
  body?: ZodType
  /** The success body; none means the endpoint answers 204 without one. */
  response?: ZodType
}
 
type Part = 'params' | 'query' | 'body'
 
/** What a caller sends for one part: the schema's input, so coerced and defaulted fields stay optional. */
export type EndpointInput<E extends Endpoint, K extends Part> = E extends {
  [P in K]: infer S extends ZodType
}
  ? input<S>
  : never
 
/** What a caller gets back: the parsed success body, or void for a 204. */
export type EndpointResponse<E extends Endpoint> = E extends {
  response: infer S extends ZodType
}
  ? output<S>
  : void
 
/** Fills `:name` segments, encoded so a value cannot add path segments. */
export function apiPath(path: string, params: Record<string, string> = {}): string {
  return path.replace(/:(\w+)/g, (_match, name: string) => {
    const value = params[name]
    if (value === undefined) throw new Error(`Missing path param ${name}`)
 
    return encodeURIComponent(value)
  })
}