fix: 通知 SSE 长连接被 Nginx 60s 超时掐断
This commit is contained in:
@@ -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))),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user