I am working on a project where I need to display an event that occurs in the backend on the frontend. Since it is a one-way communication, I have decided to use SSE (Server Sent Events) in nestjs to push the event to the frontend. The setup, as per the documentation, is quite straightforward:
@Sse('sse')
sse(): Observable<MessageEvent> {
return interval(1000).pipe(map((_) => ({ data: { hello: 'world' } })));
}
Although this setup works, I now want to push the actual "event" happening in the backend instead of using interval
. Here is my current setup:
@Injectable()
export class StocksService {
public stocks: Stock[] = [
{
id: 1,
symbol: 'Stock #1',
bid: 500,
ask: 500,
}
];
constructor(private eventEmitter: EventEmitter2) {}
create(createStockDto: CreateStockDto) {
const stock = {
id: this.stocks.length + 1,
...createStockDto,
};
this.stocks.push(stock);
const stockCreatedEvent = new StockCreatedEvent();
stockCreatedEvent.symbol = stock.symbol;
stockCreatedEvent.ask = stock.ask;
stockCreatedEvent.bid = stock.bid;
this.eventEmitter.emit('stock.created', stockCreatedEvent);
return stock;
}
}
The line
this.eventEmitter.emit('stock.created', stockCreatedEvent);
emits the event, and I can see it in the console using a listener:
@Injectable()
export class StockCreatedListener {
@OnEvent('stock.created')
handleStockCreatedEvent(event: StockCreatedEvent) {
console.log(event);
}
}
Now, I want to push this data to the frontend using SSE. I tried creating an Observable
like this:
@Sse('sse')
@OnEvent('stock.created')
sse(event: StockCreatedEvent): Observable<MessageEvent> {
const obj = of(event);
return obj.pipe(map((_) => ({ data: event})));
}
However, when I visit the URL http://localhost:3000/sse
, nothing happens. It doesn't log anything or return any stream. Do I need an observable here, or should I be using a subject?
I would appreciate any help or guidance on this. You can also check out the repository for more specific details.