aniftyco / kubit

Full stack web framework for Node.js
https://kubitjs.com/
MIT License
26 stars 2 forks source link

1st party package: SSE #20

Open joshmanders opened 11 months ago

joshmanders commented 11 months ago

The core team is working on a SSE package for v6, but we're staying on v5 for a while until the ecosystem catches up to the changes. So we'll need a better implementation of SSE events and this is what I was thinking.

The package registers a service provider that sets up an endpoint /events to connect to with a EventSource object on the client side. It also publishes a config/sse.ts file that from the top of my head just gives a you the ability to define what events can be broadcasted to the endpoint from the built in Event system.

So say you have this in your config:

export default sseConfig({
  events: ['chat:*'],
});

This will then start listening and broadcasting all chat: prefixed events to the endpoint. So in your application you can just do:

import Event from '@ioc:Adonis/Core/Event'

import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';

export default class ChatController {
  public async create({ auth, request, response }: HttpContextContract) {
    const { message } = request.input('message');

    Event.emit('chat:message', { user: auth.user.name, message });

    return response.status(204); // successful but no content.
  }
}

This will then broadcast that event details to the client side.