elysiajs / elysia

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

Async derive type does not exist in WS data #612

Closed vrn-hkz closed 5 months ago

vrn-hkz commented 5 months ago

What version of Elysia.JS is running?

1.0.13

What platform is your computer?

Linux 6.8.0-76060800daily20240311-generic x86_64 x86_64

What steps can reproduce the bug?

const app = new Elysia()
    // .use(jwtPlugin)
    .group(
        '/ws',
        {
            query: t.Object({
                token: t.String(),
            }),
        },
        (app) =>
            app
                .derive({ as: 'scoped' }, async ({ jwt, query: { token }, set }) => {
                    const tokenValues = await jwt.verify(token);
                    if (!tokenValues || !tokenValues.user) {
                        set.status = 401;
                        return buildErrorResponse('Unauthorized');
                    }
                    const user = JSON.parse(tokenValues.user as string);
                    console.log('derive user', user);
                    return {
                        user,
                    };
                })
                .ws('/', {
                    open: async ({ id, data: { user } }) => {
                        //                    ^ TS2339: Property user does not exist on type xxx
                        console.log('opened');

                        console.log('opened user', user); // <- user object actually exists. Only type is no getting inferred
                    },
                }),
    );

If derive is not async, the type is inferred in WS properly, but with async it does not show up

What is the expected behavior?

Async derived types are correctly inferred

What do you see instead?

No response

Additional information

No response

vrn-hkz commented 5 months ago

It was because I was returning a response in the derive like as if it was a handler hook. return buildErrorResponse('Unauthorized'); I have moved this logic into a onBeforeHandle hook and everything is fine now