disable cache

This commit is contained in:
SrGooglo 2025-02-18 04:22:56 +00:00
parent 37ab0184c2
commit c1feeb0221

View File

@ -1,70 +1,82 @@
import SSEChannel from "../SSEChannel"
export default class SSEManager {
channels = new Map()
channels = new Map()
createChannel(channelId) {
const channel = new SSEChannel({
id: channelId
})
createChannel(channelId) {
const channel = new SSEChannel({
id: channelId,
})
this.channels.set(channelId, channel)
this.channels.set(channelId, channel)
return channel
}
return channel
}
sendToChannel(channelId, ...args) {
const channel = this.channels.get(channelId)
sendToChannel(channelId, ...args) {
if (!this.channels.has(channelId)) {
this.createChannel(channelId)
}
if (!channel) {
throw new Error("Channel not found")
}
const channel = this.channels.get(channelId)
channel.cache.push(args)
channel.eventBus.emit("data", ...args)
}
if (!channel) {
throw new Error("Channel not found")
}
connectToChannelStream = (channelId, req, res) => {
const channel = this.channels.get(channelId)
//channel.cache.push(args)
channel.eventBus.emit("data", ...args)
}
if (!channel) {
throw new OperationError(404, `Channel [${channelId}] not found`)
}
connectToChannelStream = (channelId, req, res, { initialData } = {}) => {
let channel = this.channels.get(channelId)
channel.clients.add(req)
if (!channel) {
channel = this.createChannel(channelId)
//throw new OperationError(404, `Channel [${channelId}] not found`)
}
res.setHeader("Content-Type", "text/event-stream")
res.setHeader("Cache-Control", "no-cache")
res.setHeader("Connection", "keep-alive")
res.status(200)
channel.clients.add(req)
if (channel.cache.length > 0) {
for (const oldData of channel.cache) {
this.writeJSONToResponse(res, oldData)
}
}
res.setHeader("Content-Type", "text/event-stream")
res.setHeader("Cache-Control", "no-cache")
res.setHeader("Connection", "keep-alive")
res.status(200)
channel.eventBus.on("data", (data) => {
this.writeJSONToResponse(res, data)
})
// if (channel.cache.length > 0) {
// for (const oldData of channel.cache) {
// this.writeJSONToResponse(res, oldData)
// }
// }
req.on("close", () => {
channel.clients.delete(req)
this.writeJSONToResponse(res, {
event: "connected",
})
if (channel.clients.size === 0) {
this.channels.delete(channelId)
}
if (initialData) {
this.writeJSONToResponse(res, initialData)
}
res.end()
})
}
channel.eventBus.on("data", (data) => {
this.writeJSONToResponse(res, data)
})
writeJSONToResponse = (res, data) => {
console.log(`[SSE] Sending data >`, data)
res.write("data: " + JSON.stringify(data) + "\n\n")
}
req.on("close", () => {
channel.clients.delete(req)
getChannel = (channelId) => {
return this.channels.get(channelId)
}
}
if (channel.clients.size === 0) {
this.channels.delete(channelId)
}
res.end()
})
}
writeJSONToResponse = (res, data) => {
res.write("data: " + JSON.stringify(data) + "\n\n")
}
getChannel = (channelId) => {
return this.channels.get(channelId)
}
}