import { AnyRouter } from './Router' import { inferFetcher, inferRoutes } from './helpers' import { Config, DEFAULT_CONFIG } from './config' export type RouteFetcher = inferFetcher< inferRoutes > type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never export type CreateRouteFetcherReturn = UnionToIntersection> export type Fetcher = (url: string, params: string) => Promise export type FetcherConfiguration = { /** * Base url of the nextjs backend without '/api'. */ baseUrl: string /** * Fetcher implementation. */ fetcher?: Fetcher } & Partial const defaultFetcher: Fetcher = (url, params) => fetch(url, { method: 'POST', body: params, }) export const createRouteFetcher = ({ baseUrl, stringify = DEFAULT_CONFIG.stringify, parser = DEFAULT_CONFIG.parser, fetcher = defaultFetcher, }: FetcherConfiguration): CreateRouteFetcherReturn => ((path: unknown, params: unknown) => fetcher(`${baseUrl}/api/${path}`, stringify({ input: params })) .then((r) => r.text()) .then((v) => parser(v).result)) as unknown as CreateRouteFetcherReturn< inferRoutes >