elysiajs / elysia

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

Support for classes and getter fields #670

Open m1212e opened 1 month ago

m1212e commented 1 month ago

What is the problem this feature would solve?

Take this example:

import { Elysia, t } from "elysia";

class Example {
    field1: string;
    field3?: string;

    constructor(
        private field2: string,
        field1: string,
        field3?: string,
    ) {
        this.field1 = field1;
        this.field3 = field3;
        console.log("Hello, Elysia!");

    }

  get getterField() {
    return this.field2;
  }
}

const app = new Elysia({normalize: true})
    .get(
        "/",
        () => {
            return new Example("field2", "field1");
        },
        {
            response: t.Object({
                field1: t.String(),
                field3: t.Optional(t.String()),
        // getterField: t.String()
            }),
        },
    )
  .get(
        "/2",
        () => {
            return {
        get field1() {
          return "field1";
        },
        field3: "field3",
      };
        },
        {
            response: t.Object({
                field1: t.String(),
                field3: t.Optional(t.String()),
            }),
        },
    )
    .listen(3000);

console.log(
    `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`,
);

Both endpoints are erroring: The first one returns a stringified object: [object Object] And the second one returns {"name":"TypeError","message":"Attempted to assign to readonly property."}

What is the feature you are proposing to solve the problem?

I think converting classes and objects using a getter to a serializeable object is pretty doable by using the spread syntax to copy over the object after the handler.

What alternatives have you considered?

No response