带有 nestJs 的服务器发送事件(SSE)

问题描述 投票:0回答:0

我是 nestJs 的新手,现在我需要在 nestJs 中实现 sse,在 nestJs 中,他们有一个名为 @Sse 的特殊装饰器来建立客户端和服务器之间的 sse 连接。

如果我使用这个@Sse 装饰器,我需要返回可观察对象。 observables 就像一个事件,每当发出新事件时,observar 将接收新发出的数据。

notification.controller.ts

import { Public } from 'src/decorators';
import { Observable } from 'rxjs';
import { FastifyReply } from 'fastify';
import { NotificationService } from './notification.service';

import { Sse, Controller, Res } from '@nestjs/common';

@Public()
@Controller()
export class NotificationController {
  constructor(private notificationService: NotificationService) {}
  @Sse('notifications')
  async sendNotification(@Res() reply: FastifyReply): Promise<Observable<any>> {
    return await this.notificationService.handleConnection();
  }
}

notification.service.ts

import { Injectable } from '@nestjs/common';
import { Subject } from 'rxjs';

@Injectable()
export class NotificationService {
  notificationEvent: Subject<any> = new Subject();
  async handleConnection() {
    setInterval(() => {
      this.notificationEvent.next({ data: { message: 'Hello World' } });
    }, 1000);
    return this.notificationEvent.asObservable();
  }
}

我想用一个例子来证明这个问题,让我们考虑使用AB,让我们考虑用户A首先连接sse连接。那么 setInterval 方法将从服务文件中触发,因此每 1 秒用户 A 将从服务器接收消息 { message: 'Hello World' }。现在考虑用户 B 连接到 sse。

现在发生的是,它也触发了 setInterval 方法,所以 observable 发出了事件,用户 A 和 B 都收到了这个事件。我认为这对我来说是个问题。

我的要求是,用户需要连接到 sse,但我想根据角色和某些事情从服务器发送消息,我想为特定用户发送一些消息,为其他一些用户发送一些消息,这就是我的要求。如果我想实现这个,我需要实现什么?

Observable 这可能吗?或者我需要找到任何其他方法。如果您知道答案,请分享您的答案。

nestjs observable sse
© www.soinside.com 2019 - 2024. All rights reserved.