@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
80 lines (79 loc) • 2.43 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;
}
/**
* Asks the socket to emit no further messages until "resumeMessages" is
* called. "ServerTCP" does so while "maxConcurrentMessages" messages of the
* peer are being handled. A socket class that does not implement it keeps
* emitting messages as it reads them.
*/
pauseMessages() { }
resumeMessages() { }
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);
}
}