@nestjs/microservices
Version:
Nest - modern, fast, powerful node.js web framework (@microservices)
72 lines (71 loc) • 2.09 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.handleDataError(e);
}
}
/**
* Surfaces a framing error on the underlying socket and closes it.
* Pass "destroy" for a peer that cannot be trusted to answer a FIN.
*/
handleDataError(e, { destroy = false } = {}) {
this.socket.emit("error" /* TcpEventsMap.ERROR */, e.message);
if (destroy) {
this.socket.destroy();
}
else {
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);
}
}