gaurishhs / elysia-decorators

Decorators support plugin for Elysia
MIT License
65 stars 6 forks source link

Quick Question #12

Closed JacobwBruce closed 6 months ago

JacobwBruce commented 6 months ago

How would do you strongly type handler function? I can't seem to find any types for this within the existing Elysia package


@Controller("/auth")
export class AuthController {
  @Post("/login", loginDocs)
  async login({ request, error }: THIS_IT_HERE) {}
}
gaurishhs commented 6 months ago

I'll look into this

JacobwBruce commented 6 months ago

Update I found out you can use the type: Context which optionally can have types passed in to specify the shape of certain properties. Here I use Context (which has all of the properties of an Elysia handler function), then strongly type the shape of the incoming body


import { Controller, Post } from "elysia-decorators";
import { loginDocs } from "./docs";
import { type Context } from "elysia";

@Controller("/auth")
export class AuthController {
  @Post("/login", loginDocs)
  async login({
    body,
    error,
    jwt,
  }: Context<{
    body: {
      username: string;
      password: string;
    };
  }> & { jwt: any }) {
    if (body.username !== "admin" || body.password !== "admin") {
      return error(401, {
        message: "Invalid credentials",
      });
    }

    const token = await jwt.sign({ username: body.username });

    return { token };
  }
}