elysiajs / elysia

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

derive body is not parsed #589

Closed yadsbah closed 3 months ago

yadsbah commented 3 months ago

What version of Elysia.JS is running?

No response

What platform is your computer?

No response

What steps can reproduce the bug?

Body is not parsed before derive. the body is String.

export const doesBrandExistPlugin = (app: Elysia) => {
  return app.derive(
    {
      as: "scoped",
    },
    async ({ body }) => {
      const { id } = body;
      const brand = await db.brands.findFirst({
        where: {
          id,
        },
        include: {
          title: true,
        },
      });
      return {
        brand,
      };
    }
  );
};

What is the expected behavior?

No response

What do you see instead?

No response

Additional information

No response

kidqueb commented 3 months ago

You're probably thinking more of resolve which runs after route validation, but also from a typesafety perspective the plugin is unaware of any validation that had previously been defined.

To guarantee the body is validated with an id you can add a guard before calling derive

function doesBrandExistPlugin(app: Elysia) {
  return app
    .guard({
      body: t.Object({ id: t.String() }),
    })
    .derive({ as: "global" }, ({ body }) => {
      body.id; // string
      return { YAY: true };
    });
}

const app = new Elysia()
  .use(doesBrandExistPlugin)
  .get('/', ({ YAY }) => {
    return YAY; // boolean
  })
yadsbah commented 3 months ago

You're probably thinking more of resolve which runs after route validation, but also from a typesafety perspective the plugin is unaware of any validation that had previously been defined.

To guarantee the body is validated with an id you can add a guard before calling derive

function doesBrandExistPlugin(app: Elysia) {
  return app
    .guard({
      body: t.Object({ id: t.String() }),
    })
    .derive({ as: "global" }, ({ body }) => {
      body.id; // string
      return { YAY: true };
    });
}

const app = new Elysia()
  .use(doesBrandExistPlugin)
  .get('/', ({ YAY }) => {
    return YAY; // boolean
  })

Using Guard fixed the problem. Thanks