Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
wip JSONStream
  • Loading branch information
Sticks committed Feb 15, 2023
1 parent 8838385 commit 7df63f2
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 4 deletions.
22 changes: 19 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Expand Up @@ -14,6 +14,7 @@
"author": "sticksdev",
"license": "MIT",
"devDependencies": {
"@types/eventsource": "^1.1.11",
"@types/jest": "^29.4.0",
"@typescript-eslint/eslint-plugin": "^5.51.0",
"@typescript-eslint/parser": "^5.51.0",
Expand All @@ -26,7 +27,8 @@
"typescript": "^4.9.5"
},
"dependencies": {
"axios": "^1.3.2"
"axios": "^1.3.2",
"eventsource": "^2.0.2"
},
"scripts": {
"compile": "tsc -p tsconfig.build.json",
Expand Down
50 changes: 50 additions & 0 deletions src/classes/JSONStream.ts
@@ -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();
}
}
3 changes: 3 additions & 0 deletions src/main.ts
@@ -1,3 +1,4 @@
import { JSONStream } from './classes/JSONStream';
import { RESTNotifyClient } from './classes/REST';

export class notifer {
Expand All @@ -7,3 +8,5 @@ export class notifer {
this.REST = new RESTNotifyClient(url);
}
}

export { JSONStream };

0 comments on commit 7df63f2

Please sign in to comment.