elysiajs / elysia

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

How can I use `app.server?.publish` from a plugin? #389

Closed misaelabanto closed 9 months ago

misaelabanto commented 9 months ago

I have a plugin for handle all requests to /votes endpoint:

export const votes = new Elysia()
    .use(voteModel)
    .get('/votes', () => voteRepository.getVotes(), {
        response: 'votes',
        detail: {
            tags: ['votes'],
        },
    })
    .post(
        '/votes',
        ({ body }) => {
            const result = votes.server?.publish('party', 'vote');
            console.log(result);
            return voteRepository.create(body);
        },
        {
            body: 'vote.create',
            response: 'vote',
            detail: {
                tags: ['votes'],
            },
        }
    )
    .delete('/votes/:id', ({ params }) => voteRepository.delete(params.id), {
        params: t.Object({
            id: t.String(),
        }),
        detail: {
            tags: ['votes'],
        },
    });

This is my ws plugin:

export const wsPlugin = new Elysia().ws('/ws', {
    open(ws) {
        ws.subscribe('party');
    },
    message(ws, message) {
        ws.send(message);
    },
});

The result from votes.server?.publish('party', 'vote'); is always undefined. How can I reference the app defined in index.ts from my plugin?

vastamaki commented 9 months ago

In our API we define the websocket plugin as the last thing before .listen() and it works correctly, do you have the latest version of Elysia? Also, I believe Discord would be a more appropriate channel to ask this kind of questions! 🙂

misaelabanto commented 9 months ago

All right! I will try the very new version and, if it does not work, I will ask the question on Discord. Thank you