elysiajs / elysia

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

Scoped instances won't execute hooks #158

Closed emilianomon closed 11 months ago

emilianomon commented 1 year ago

Hey!

I am facing this strange behavior where if I set an instance to scoped, middlewares that are used by the instance are not triggered.

const scoped = new Elysia({ scoped: true })
.use(app)
.use(authorizationMiddleware)
.get('/user', ({ auth }) => {

  console.log('User retrieved!'); // Triggers

  return {
    email: auth.user.email,
    id: auth.user.id,
  };
})
export const app = new Elysia({ name: 'app' })
.onRequest(() => {
  console.log('"app" instance executed.'); // Won't be triggered.
})
export const authorizationMiddleware = new Elysia()
.use(app)
.derive(async () => {

  // ...
  // This also won't be triggered.

  return {
    auth: {
      user,
    },
  };
});

Is this expected?

SaltyAom commented 1 year ago

This should be fixed in #103

gtrabanco commented 1 year ago

I made a plugin I have tested on 0.7.9.

When I use scoped: true in this line: https://github.com/gtrabanco/elysia-inject-html/blob/145d9ebf7a2d2057489e2aeaf0a295265445cf51/src/index.ts#L63

The events are not dispatched.

SaltyAom commented 11 months ago

Should be fixed in the latest version.

Reproducible code:

import { Elysia } from '../src'

const app = new Elysia({ name: 'app' }).onRequest(() => {
    console.log('"app" instance executed.') // Executed
})

export const authorizationMiddleware = new Elysia()
    .use(app)
    .derive(async () => {
        return {
            auth: {
                user: ''
            }
        }
    })

const scoped = new Elysia({ scoped: true })
    .use(app)
    .use(authorizationMiddleware)
    .get('/user', ({ auth }) => {
        return auth
    })
    .listen(3000)

Feels free to reopen if the issue still persists.