( route: string, info: RouteInfo<Params, Search>, postInfo: PostInfo<Body, Result> )
| 211 | const emptySchema = z.object({}); |
| 212 | |
| 213 | export function makePostRoute< |
| 214 | Params extends z.ZodSchema, |
| 215 | Search extends z.ZodSchema, |
| 216 | Body extends z.ZodSchema, |
| 217 | Result extends z.ZodSchema |
| 218 | >( |
| 219 | route: string, |
| 220 | info: RouteInfo<Params, Search>, |
| 221 | postInfo: PostInfo<Body, Result> |
| 222 | ): PostRouteBuilder<Params, Search, Body, Result> { |
| 223 | const urlBuilder = createRouteBuilder(route, info); |
| 224 | |
| 225 | const routeBuilder: PostRouteBuilder<Params, Search, Body, Result> = ( |
| 226 | body: z.input<Body>, |
| 227 | p?: z.input<Params>, |
| 228 | search?: z.input<Search>, |
| 229 | options?: FetchOptions |
| 230 | ): Promise<z.output<Result>> => { |
| 231 | const safeBody = postInfo.body.safeParse(body); |
| 232 | if (!safeBody.success) { |
| 233 | throw new Error( |
| 234 | `Invalid body for route ${info.name}: ${safeBody.error.message}` |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | return fetch(urlBuilder(p, search), { |
| 239 | ...options, |
| 240 | method: "POST", |
| 241 | body: JSON.stringify(safeBody.data), |
| 242 | headers: { |
| 243 | ...(options?.headers || {}), |
| 244 | "Content-Type": "application/json" |
| 245 | } |
| 246 | }) |
| 247 | .then((res) => { |
| 248 | if (!res.ok) { |
| 249 | throw new Error(`Failed to fetch ${info.name}: ${res.statusText}`); |
| 250 | } |
| 251 | return res.json() as Promise<z.output<Result>>; |
| 252 | }) |
| 253 | .then((data) => { |
| 254 | const result = postInfo.result.safeParse(data); |
| 255 | if (!result.success) { |
| 256 | throw new Error( |
| 257 | `Invalid response for route ${info.name}: ${result.error.message}` |
| 258 | ); |
| 259 | } |
| 260 | return result.data; |
| 261 | }); |
| 262 | }; |
| 263 | |
| 264 | routeBuilder.params = undefined as z.output<Params>; |
| 265 | routeBuilder.paramsSchema = info.params; |
| 266 | routeBuilder.search = undefined as z.output<Search>; |
| 267 | routeBuilder.searchSchema = info.search; |
| 268 | routeBuilder.body = undefined as z.output<Body>; |
| 269 | routeBuilder.bodySchema = postInfo.body; |
| 270 | routeBuilder.result = undefined as z.output<Result>; |
nothing calls this directly
no test coverage detected