2023-06-07 12:13:52 +09:00
|
|
|
import {PassThrough, Stream} from "stream";
|
2023-06-07 14:52:04 +09:00
|
|
|
import {parseJSON} from "./index";
|
2023-06-07 12:13:52 +09:00
|
|
|
|
|
|
|
export class WriteEventStream {
|
|
|
|
public stream: PassThrough;
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
this.stream = new PassThrough();
|
|
|
|
}
|
|
|
|
|
|
|
|
write(event: string, data: string) {
|
|
|
|
if (!this.stream.closed) {
|
|
|
|
this.stream.write(`event: ${event}\n`);
|
2023-06-07 14:52:04 +09:00
|
|
|
this.stream.write(`data: ${JSON.stringify(data)}\n\n`);
|
2023-06-07 12:13:52 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
end(cb?: () => void) {
|
|
|
|
this.stream?.end(cb);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export class ReadEventStream {
|
|
|
|
private readonly stream: Stream;
|
|
|
|
|
2023-06-07 14:52:04 +09:00
|
|
|
constructor(stream: Stream) {
|
2023-06-07 12:13:52 +09:00
|
|
|
this.stream = stream;
|
|
|
|
}
|
|
|
|
|
|
|
|
read(dataCB: ({event, data}: { event: string, data: string }) => void, doneCB: () => void) {
|
|
|
|
let buffer = '';
|
|
|
|
this.stream.on('data', data => {
|
|
|
|
buffer += data.toString();
|
|
|
|
let index = buffer.indexOf('\n\n');
|
|
|
|
while (index !== -1) {
|
|
|
|
const v = buffer.slice(0, index).trim();
|
|
|
|
buffer = buffer.slice(index + 2);
|
|
|
|
|
|
|
|
const lines = v.split('\n');
|
|
|
|
const lineEvent = lines[0].replace('event: ', '');
|
|
|
|
const lineData = lines[1].replace('data: ', '');
|
2023-06-07 14:52:04 +09:00
|
|
|
dataCB({event: lineEvent, data: JSON.parse(lineData)});
|
2023-06-07 12:13:52 +09:00
|
|
|
index = buffer.indexOf('\n\n');
|
|
|
|
}
|
|
|
|
});
|
|
|
|
this.stream.on('close', doneCB);
|
|
|
|
}
|
|
|
|
}
|