elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
9.74k stars 207 forks source link

Fixing types recognition in elysia.route and hook handlers (before and after) #738

Open gabrielguim opened 1 month ago

gabrielguim commented 1 month ago

Context:

i'm creating my elysia app using a clean architecture approach, so i was typing my adapter for http method handlers and middlewares when i faced this "type" problem.

// request-parser
const requestParser = (controller: Controller) => (context: Context) =>
  controller(ElysiaHttpRequest.from(context), ElysiaHttpResponse.from(context), () => {});

// ElysiaServer adapter
export default class ElysiaServer implements Server {
  ...
  start(port: number, callback?: () => void) {
    this.server = this.routes
        .reduce((elysiaServer, route) => {
          const { path, method, controller, middlewares } = route;

          return elysiaServer.route(method, path, requestParser(controller), {
            // forced to use this empty config
            config: {},
            // forced to type my handler as any[] because beforeHandle param does not match with "Context"
            // so my "requestParser" does not match as the required type of beforeHandle
            beforeHandle: middlewares?.map((middleware) => requestParser(middleware)) as any[],
          });
        }, new Elysia({ prefix: '/api' }))
        .listen(port, () => {
          console.log(`Server started. Listening on port ${port}`);

          callback?.();
        });
  }
}

the problem

I was forced to pass a empty config object instead just using the default config as the private "add" method already do. elysia

Solving this problem, i faced another one while typing my context parameter as Context, the type inference does not recognize the object as Context properly. elysia-2