Skip to content

FR, Bug Report - Guard chaining #1045

Open
@Heniker

Description

@Heniker

What is the problem this feature would solve?

Elysia handles multiple .guard calls very strangely.

See the following example:

import { Elysia, t } from 'elysia'

const OnlyStrongPassword = new Elysia()
  .guard({
    body: t.Object({ password: t.Literal('strong-password') }, { additionalProperties: true }),
    beforeHandle() {
      console.log('Checking password...')
    },
  })
  .as('plugin')

const app = new Elysia()
  .use(OnlyStrongPassword)
  .guard({
    body: t.Object({ username: t.Literal('Jhon') }, { additionalProperties: true }),
    beforeHandle() {
      console.log('Checking name...')
    },
  })
  .post('/test', ({ body }) => {
    return 'Hello ' + body.username
  })
  .listen(3000)

const response = await app
  .handle(
    new Request('http://localhost/test', {
      // notice how password is wrong
      body: JSON.stringify({ password: 'weak-password', username: 'Jhon' }),
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    })
  )
  .then((res) => res.text())

console.log(response)

This logs:

Checking password...
Checking name...
Hello Jhon

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 and body in the other correctly.

The proposed solution is to allow .guard chaining by turning resulting value into intersection.

Using t.Intersect instead of replacing value in mergeHook function worked fine for my use-case.

export const mergeHook = (

The types in MergeSchema must also be updated.

export interface MergeSchema<

What alternatives have you considered?

Throw Error or warn about chaining multiple .guard calls.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestquestionFurther information is requested

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions