11import path from "node:path" ;
2- import type { RouterTypes } from "bun" ;
2+ import type { BunRequest , RouterTypes , Server } from "bun" ;
3+ import { WaveKitResponse } from "./response" ;
34
45const isDev = process . env . NODE_ENV === "development" ;
56
@@ -9,6 +10,17 @@ const defaultRoutesDir = isDev
910
1011const defaultOutDir = path . join ( process . cwd ( ) , "build" ) ;
1112
13+ type WaveKitContext = {
14+ req : BunRequest ;
15+ res : WaveKitResponse ;
16+ html : typeof WaveKitResponse . html ;
17+ json : typeof WaveKitResponse . json ;
18+ } ;
19+
20+ export type WaveKitHandler = (
21+ c : WaveKitContext ,
22+ ) => Response | Promise < Response > ;
23+
1224type BuildRoutesProps = {
1325 routes : Record < string , string > ;
1426} ;
@@ -18,14 +30,43 @@ export async function buildRoutes({
1830} : BuildRoutesProps ) : Promise <
1931 Record < string , RouterTypes . RouteHandlerObject < string > >
2032> {
33+ const contextStore = new Map ( ) ;
2134 const rawRoutes = Object . entries ( routes ) ;
2235 const routesWithHandlers = rawRoutes . map ( async ( [ path , handlerPath ] ) => {
2336 const handler = ( await import (
2437 handlerPath
2538 ) ) as RouterTypes . RouteHandlerObject < string > ;
26- return [ path , handler ] ;
39+ const contextHandler : RouterTypes . RouteHandlerObject < string > = { } ;
40+ for ( const method of Object . keys ( handler ) ) {
41+ const methodHandler = handler [
42+ method as RouterTypes . HTTPMethod
43+ ] as unknown as WaveKitHandler ;
44+ if ( ! methodHandler ) return ;
45+ contextHandler [ method as RouterTypes . HTTPMethod ] = (
46+ req : BunRequest ,
47+ server : Server ,
48+ ) => {
49+ const res = new WaveKitResponse ( ) ;
50+ const context = {
51+ req,
52+ res,
53+ html : WaveKitResponse . html ,
54+ json : WaveKitResponse . json ,
55+ redirect : WaveKitResponse . redirect ,
56+ set : contextStore . set ,
57+ get : contextStore . get ,
58+ } ;
59+ return methodHandler ( context ) ;
60+ } ;
61+ }
62+ return [ path , contextHandler ] ;
2763 } ) ;
28- return Object . fromEntries ( await Promise . all ( routesWithHandlers ) ) ;
64+ return Object . fromEntries (
65+ ( await Promise . all ( routesWithHandlers ) ) . filter ( Boolean ) as [
66+ string ,
67+ RouterTypes . RouteHandlerObject < string > ,
68+ ] [ ] ,
69+ ) ;
2970}
3071
3172export type CreateWaveKitProps = {
0 commit comments