-
-
Notifications
You must be signed in to change notification settings - Fork 254
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
FR, Bug Report - Guard chaining #1045
Comments
I think it's expected as far as my knowledge goes. You can try this: import { Elysia, t } from "elysia";
const passwordGuard = new Elysia().guard({
body: t.Object({
password: t.Literal("secure-password"),
}, { additionalProperties: true }),
}).as('plugin')
const bodyGuard = new Elysia()
.guard({
body: t.Object({
name: t.Literal("John"),
}, { additionalProperties: true }),
}).as('plugin')
const app = new Elysia()
.use(bodyGuard)
.use(passwordGuard)
.post("/hello", ({ body }) => {
return body;
});
app.listen(9000);
const response = await app
.handle(
new Request("http://localhost:9000/hello", {
body: JSON.stringify({ password: "weak-password", username: "Jhon" }),
method: "POST",
headers: { "Content-Type": "application/json" },
}),
)
.then((res) => res.text());
console.log(response); It should return something like this:
|
No, that doesn't really work. const response = await app
.handle(
new Request("http://localhost:9000/hello", {
// now username is wrong, but request still passes
body: JSON.stringify({ password: "secure-password", username: "Bad Username" }),
method: "POST",
headers: { "Content-Type": "application/json" },
}),
)
.then((res) => res.text());
console.log(response); |
Hi, this happens because Elysia overrides the properties of a hook when it is a type (in this case "body"). This means it only checks if the username is valid. |
What is the problem this feature would solve?
Elysia handles multiple
.guard
calls very strangely.See the following example:
This logs:
Despite provided password being wrong.
What is the feature you are proposing to solve the problem?
Elysia already partially handles combining multiple guards - e.g. it's possible to use
query
in one guard andbody
in the other correctly.The proposed solution is to allow
.guard
chaining by turning resulting value intointersection
.Using
t.Intersect
instead of replacing value inmergeHook
function worked fine for my use-case.elysia/src/utils.ts
Line 200 in caaf17c
The types in
MergeSchema
must also be updated.elysia/src/types.ts
Line 543 in caaf17c
What alternatives have you considered?
Throw
Error
or warn about chaining multiple.guard
calls.The text was updated successfully, but these errors were encountered: