2019-07-30 09:05:41 -05:00
|
|
|
import { loadAdapter } from '../Adapters/AdapterLoader';
|
|
|
|
|
import { WSAdapter } from '../Adapters/WebSocketServer/WSAdapter';
|
2016-08-12 13:25:24 -04:00
|
|
|
import logger from '../logger';
|
2019-07-30 09:05:41 -05:00
|
|
|
import events from 'events';
|
2021-07-25 02:54:28 +03:00
|
|
|
import { inspect } from 'util';
|
2016-03-10 14:27:00 -08:00
|
|
|
|
|
|
|
|
export class ParseWebSocketServer {
|
|
|
|
|
server: Object;
|
|
|
|
|
|
2019-07-30 20:40:54 -07:00
|
|
|
constructor(server: any, onConnect: Function, config) {
|
2019-07-30 09:05:41 -05:00
|
|
|
config.server = server;
|
2019-07-30 20:40:54 -07:00
|
|
|
const wss = loadAdapter(config.wssAdapter, WSAdapter, config);
|
2019-07-30 09:05:41 -05:00
|
|
|
wss.onListen = () => {
|
2016-08-12 13:25:24 -04:00
|
|
|
logger.info('Parse LiveQuery Server starts running');
|
2019-07-30 09:05:41 -05:00
|
|
|
};
|
2020-07-13 17:13:08 -05:00
|
|
|
wss.onConnection = ws => {
|
|
|
|
|
ws.on('error', error => {
|
2020-02-19 03:30:23 -06:00
|
|
|
logger.error(error.message);
|
2021-07-25 02:54:28 +03:00
|
|
|
logger.error(inspect(ws, false));
|
2020-02-19 03:30:23 -06:00
|
|
|
});
|
2016-03-10 14:27:00 -08:00
|
|
|
onConnect(new ParseWebSocket(ws));
|
|
|
|
|
// Send ping to client periodically
|
2016-12-07 15:17:05 -08:00
|
|
|
const pingIntervalId = setInterval(() => {
|
2016-03-10 14:27:00 -08:00
|
|
|
if (ws.readyState == ws.OPEN) {
|
|
|
|
|
ws.ping();
|
|
|
|
|
} else {
|
|
|
|
|
clearInterval(pingIntervalId);
|
|
|
|
|
}
|
2019-07-30 09:05:41 -05:00
|
|
|
}, config.websocketTimeout || 10 * 1000);
|
|
|
|
|
};
|
2020-07-13 17:13:08 -05:00
|
|
|
wss.onError = error => {
|
2019-11-22 15:23:04 -06:00
|
|
|
logger.error(error);
|
|
|
|
|
};
|
2019-07-30 09:05:41 -05:00
|
|
|
wss.start();
|
2016-03-10 14:27:00 -08:00
|
|
|
this.server = wss;
|
|
|
|
|
}
|
2019-07-30 09:05:41 -05:00
|
|
|
|
|
|
|
|
close() {
|
|
|
|
|
if (this.server && this.server.close) {
|
|
|
|
|
this.server.close();
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-03-10 14:27:00 -08:00
|
|
|
}
|
|
|
|
|
|
2019-07-30 09:05:41 -05:00
|
|
|
export class ParseWebSocket extends events.EventEmitter {
|
2016-03-10 14:27:00 -08:00
|
|
|
ws: any;
|
|
|
|
|
|
|
|
|
|
constructor(ws: any) {
|
2019-07-30 09:05:41 -05:00
|
|
|
super();
|
2020-07-13 17:13:08 -05:00
|
|
|
ws.onmessage = request =>
|
2019-07-30 20:40:54 -07:00
|
|
|
this.emit('message', request && request.data ? request.data : request);
|
2019-07-30 09:05:41 -05:00
|
|
|
ws.onclose = () => this.emit('disconnect');
|
2016-03-10 14:27:00 -08:00
|
|
|
this.ws = ws;
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-24 15:47:41 -05:00
|
|
|
send(message: any): void {
|
2016-03-10 14:27:00 -08:00
|
|
|
this.ws.send(message);
|
|
|
|
|
}
|
|
|
|
|
}
|