mirror of
https://github.com/gosticks/DefinitelyTyped.git
synced 2026-11-29 09:41:45 +00:00
rolling websocketjson stream in
This commit is contained in:
@@ -2,7 +2,31 @@
|
||||
import * as ShareDB from 'sharedb';
|
||||
import * as http from 'http';
|
||||
import * as WebSocket from 'ws';
|
||||
import { WebSocketJSONStream } from './websocketJSONStream';
|
||||
import {Duplex} from 'stream';
|
||||
|
||||
//Adapted from https://github.com/avital/websocket-json-stream
|
||||
class WebSocketJSONStream extends Duplex {
|
||||
constructor(private readonly ws:WebSocket) {
|
||||
super({objectMode: true});
|
||||
this.ws.on('message', (msg: string) => {
|
||||
this.push(JSON.parse(msg))
|
||||
});
|
||||
this.ws.on('close', () => {
|
||||
this.push(null); // end readable stream
|
||||
this.end(); // end writable stream
|
||||
|
||||
this.emit('close');
|
||||
this.emit('end');
|
||||
});
|
||||
this.on('error', function() { ws.close(); });
|
||||
this.on('end', function() { ws.close(); });
|
||||
};
|
||||
public _read():void {};
|
||||
public _write(msg:any, encoding:string, next:Function):void {
|
||||
this.ws.send(JSON.stringify(msg));
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
const backend = new ShareDB();
|
||||
const connection = backend.connect();
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import {Duplex} from 'stream';
|
||||
import * as WebSocket from 'ws';
|
||||
|
||||
//Adapted from https://github.com/avital/websocket-json-stream
|
||||
export class WebSocketJSONStream extends Duplex {
|
||||
constructor(private readonly ws:WebSocket) {
|
||||
super({objectMode: true});
|
||||
this.ws.on('message', (msg: string) => {
|
||||
this.push(JSON.parse(msg))
|
||||
});
|
||||
this.ws.on('close', () => {
|
||||
this.push(null); // end readable stream
|
||||
this.end(); // end writable stream
|
||||
|
||||
this.emit('close');
|
||||
this.emit('end');
|
||||
});
|
||||
this.on('error', function() { ws.close(); });
|
||||
this.on('end', function() { ws.close(); });
|
||||
};
|
||||
public _read():void {};
|
||||
public _write(msg:any, encoding:string, next:Function):void {
|
||||
this.ws.send(JSON.stringify(msg));
|
||||
next();
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user