fix: 通知 SSE 长连接被 Nginx 60s 超时掐断

This commit is contained in:
2026-08-05 18:00:45 +08:00
parent 2a519a3714
commit 32343b271b
3 changed files with 35 additions and 13 deletions

View File

@@ -9,7 +9,7 @@ import {
UseGuards,
} from '@nestjs/common';
import { Request } from 'express';
import { Observable, map } from 'rxjs';
import { Observable, interval, map, merge } from 'rxjs';
import { NotificationsService } from './notifications.service';
import { NotificationQueryDto } from './dto/notification.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
@@ -53,17 +53,22 @@ export class NotificationsController {
req.on('close', () => {
this.service.unsubscribe(userId);
});
return this.service.subscribe(userId).pipe(
map((notification) => ({
data: JSON.stringify({
id: notification.id,
type: notification.type,
title: notification.title,
content: notification.content,
link: notification.link,
createdAt: notification.createdAt,
}),
} as MessageEvent)),
// 每 25s 发送一次空消息作为心跳,避免空闲连接被 Nginx 等中间层超时掐断。
// 空 data 会被前端 EventSource 收到并忽略JSON.parse 失败)。
return merge(
this.service.subscribe(userId).pipe(
map((notification) => ({
data: JSON.stringify({
id: notification.id,
type: notification.type,
title: notification.title,
content: notification.content,
link: notification.link,
createdAt: notification.createdAt,
}),
} as MessageEvent)),
),
interval(25_000).pipe(map(() => ({ data: '' } as MessageEvent))),
);
}