@nestjs/microservices
Version:
Nest - modern, fast, powerful node.js web framework (@microservices)
60 lines (59 loc) • 1.75 kB
JavaScript
import { InvalidJSONFormatException } from '../errors/invalid-json-format.exception.js';
import { NetSocketClosedException } from '../errors/net-socket-closed.exception.js';
export class TcpSocket {
socket;
isClosed = false;
get netSocket() {
return this.socket;
}
constructor(socket) {
this.socket = socket;
this.socket.on('data', this.onData.bind(this));
this.socket.on("connect" /* TcpEventsMap.CONNECT */, () => (this.isClosed = false));
this.socket.on("close" /* TcpEventsMap.CLOSE */, () => (this.isClosed = true));
this.socket.on("error" /* TcpEventsMap.ERROR */, () => (this.isClosed = true));
}
connect(port, host) {
this.socket.connect(port, host);
return this;
}
on(event, callback) {
this.socket.on(event, callback);
return this;
}
once(event, callback) {
this.socket.once(event, callback);
return this;
}
end() {
this.socket.end();
return this;
}
sendMessage(message, callback) {
if (this.isClosed) {
callback && callback(new NetSocketClosedException());
return;
}
this.handleSend(message, callback);
}
onData(data) {
try {
this.handleData(data);
}
catch (e) {
this.socket.emit("error" /* TcpEventsMap.ERROR */, e.message);
this.socket.end();
}
}
emitMessage(data) {
let message;
try {
message = JSON.parse(data);
}
catch (e) {
throw new InvalidJSONFormatException(e, data);
}
message = message || {};
this.socket.emit('message', message);
}
}