Skip to content

Commit

Permalink
see utils
Browse files Browse the repository at this point in the history
  • Loading branch information
oliver-oloughlin committed Nov 14, 2023
1 parent ccff042 commit 25eada8
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions sse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {
ServerSentEvent,
ServerSentEventStreamTarget,
} from "https://deno.land/[email protected]/http/unstable_server_sent_event.ts"

export class ServerSentEventStreamTargetPool<T> {
private targets: Map<string, ServerSentEventStreamTarget>

constructor() {
this.targets = new Map()
}

add(target: ServerSentEventStreamTarget) {
const id = crypto.randomUUID()

target.addEventListener("close", () => {
this.targets.delete(id)
})

this.targets.set(id, target)
return id
}

remove(id: string) {
this.targets.delete(id)
}

dispatchMessage(data: T) {
this.targets.forEach((target) => target.dispatchMessage(data))
}

dispatchEvent(event: ServerSentEvent) {
this.targets.forEach((target) => target.dispatchEvent(event))
}

dispatchComment(comment: string) {
this.targets.forEach((target) => target.dispatchComment(comment))
}

addEventListener(
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: AddEventListenerOptions,
) {
this.targets.forEach((target) =>
target.addEventListener(type, listener, options)
)
}
}

0 comments on commit 25eada8

Please sign in to comment.