Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
wip JSONStream
- Loading branch information
Showing
4 changed files
with
75 additions
and
4 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { EventEmitter } from 'events'; | ||
import EventSource from 'eventsource'; | ||
import { IAPIJSONStreamResponse } from '../objects/APIStreamResponses'; | ||
|
||
export class JSONStream { | ||
emiiter: EventEmitter; | ||
eventSoruce: EventSource; | ||
|
||
constructor(url = 'https://notify.hep.gg', channel: string) { | ||
this.emiiter = new EventEmitter(); | ||
this.eventSoruce = new EventSource(`${url}/${channel}/sse`); | ||
} | ||
|
||
/** | ||
* A method to get the event emitter for this class | ||
* @returns EventEmitter | ||
*/ | ||
async getEmitter() { | ||
return this.emiiter; | ||
} | ||
|
||
/** | ||
* Starts collecting the data from the SSE stream for the topic | ||
* Use the getEmitter() method to get the event emitter and handle the events (message, error) | ||
* @returns void | ||
*/ | ||
async start() { | ||
this.eventSoruce.onerror = (error) => { | ||
this.emiiter.emit('error', error); | ||
}; | ||
|
||
this.eventSoruce.onmessage = (event) => { | ||
this.emiiter.emit('message', JSON.parse(event.data)); | ||
}; | ||
} | ||
|
||
/** | ||
* Closes the connection to the SSE stream (if open) | ||
* This can't be undone, so make sure you call this method when you're done with the stream | ||
* @returns void | ||
* @throws Error | ||
*/ | ||
async destory() { | ||
if (this.eventSoruce.readyState === 0) { | ||
throw new Error('Event source is already closed'); | ||
} | ||
|
||
this.eventSoruce.close(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters