Skip to content

Instantly share code, notes, and snippets.

@bvandenbon
Last active January 30, 2021 15:03
Show Gist options
  • Save bvandenbon/188d0bd70bd68a1b3c6a7caa2002447c to your computer and use it in GitHub Desktop.
Save bvandenbon/188d0bd70bd68a1b3c6a7caa2002447c to your computer and use it in GitHub Desktop.
A Client to connect from a legacy NodeJS application (in typescript) to a NestJS Microserviceof type Transport.TCP.
import { Socket, SocketConnectOpts } from "net";
import { PromiseSocket } from "promise-socket"
export class NestTCPMicroserviceClient {
private options: SocketConnectOpts;
private socket$: PromiseSocket<Socket>;
constructor(private host: string, private port: number) {
this.options = { host: this.host, port: this.port };
}
public async connect(): Promise<void> {
if (this.socket$ != null) return;
const socket = new Socket();
socket.once("close", () => this.disconnect());
this.socket$ = new PromiseSocket(socket);
await this.socket$.connect(this.options);
}
public async disconnect() {
try {
if (this.socket$ != null) this.socket$.destroy();
} finally {
this.socket$ = null;
}
}
public async send$(pattern: any, data: any, correlationId: string): Promise<any> {
const request = this.createRequest(pattern, data, correlationId);
await this.socket$.write(request);
const jsonResponse = await this.readJSON$(this.socket$);
return JSON.parse(jsonResponse);
}
private async readJSON$(socket$: PromiseSocket<Socket>): Promise<string> {
let buffer = "";
while (true) {
const response = await socket$.read();
buffer += response.toString();
const firstHashIndex = buffer.indexOf("#");
if (firstHashIndex === -1) continue;
const length = Number(buffer.substring(0, firstHashIndex));
const foundLength = buffer.length - firstHashIndex - 1;
if (foundLength < length) continue;
return buffer.substr(firstHashIndex + 1, length);
}
}
private createRequest(pattern: any, data: any, id: string) {
const msg = { pattern, data, id };
const jsonMsg = JSON.stringify(msg);
return `${jsonMsg.length}#${jsonMsg}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment