2
\$\begingroup\$

I have built this small class as a small library to be able to talk to a server that uses CapeSoft's NetTalk library as socket library, and which uses the Whole Packet Protocol, which is a simple protocol made by CapeSoft for the communication between NetTalk Apps. However, I need to talk to this "REST" Server to get some Info for my Node App, and seeing that this Server does not work with Regular HTTP Protocol, I had to write this library myself.

I wish to know if there is any way (which I'm sure there is) to better refactor this small class and improve the comprehension of it as well as it's comments in JavaScript.

I am trying to improve my refactoring and clean coding skills. I want to be able to write the shortest code while still being simple to understand.

I would appreciate much your help to improve this. I really wish to become top programmer.

Following is my class module; any critique is welcome and well accepted.

const tls = require('tls');
const fs = require('fs');


/**
 * 
 * 
 * NetTalk Class:
 * Creates a NetTalk Object for making request to a NetTalk Service in WPP (Whole Packet Protocol).
 * 
 */
class NetTalk {
    /**
     * Creates an instance of NetTalk.
     * @param {Number} port Port through which you wish to connect to NetTalk.
     * @param {String} server Server to which to connect.
     * @param {String} certificate Route where the certificate file (*.pem) is located
     * @param {String} [verify = '0'] verify the certificate? (default="0")
     * @memberof NetTalk
     */
    constructor (port, server, certificate, verify = "0") {
        this.port = port;
        this.server = server;
        this.options = {ca:[ fs.readFileSync(certificate) ], rejectUnauthorized: false};
        this.msgSize = 0;
        this.wholePackage = '';
        this.socket = null;
        this.verify = verify;
    }

    /**
     * 
     * Connects to the NetTalk Service.
     * @memberof NetTalk
     */
    connect() {
        this.socket = tls.connect(this.port, this.server, this.options, () => {
            process.stdin.pipe(this.socket);
            process.stdin.resume();
        });


        this.socket.setTimeout(12000)
        this.socket.setEncoding('ascii');


        this.socket.on('end', () => {
            console.log('Connection terminated.');
        });


        this.socket.on('timeout', ()=> {
            console.log('Connection timed out.');
            this.socket.destroy();
        });


        return new Promise((resolve, reject) => {
            this.socket.on('ready', () => {
                console.log(`client connected on port ${this.port} to server ${this.server}`);
                resolve();
            });

            this.socket.on('error', (err) => {
                reject({err:err, func:'connect'});
            });
        });
    }

    /**
     * sends the request.
     * 
     * @param {String} reqMsg Request Message to be sent to the service.
     * @returns {Promise} {Promise.<resolve(data)|reject(error)>}
     * @memberof NetTalk
     */
    request(reqMsg) {
        return new Promise((resolve, reject) => {
            /*Adding 32 bit length Integer to the beginning of stream 
            for compatibility with WPP (Whole Packet Protocol).*/
            var message = new Buffer(reqMsg, 'binary');
            var stream = new Buffer(4 + message.length); //declares the stream to be sent.

            stream.writeInt32LE(message.length, 0); //Must be in LittleEndian for compatibility.
            message.copy(stream, 4);

            this.socket.write(stream);

            this.socket.on('data', (data) => {
                let wholePackageSize = null;

                this.wholePackage += data;
                wholePackageSize = new Buffer(this.wholePackage, 'binary');
                this.msgSize += data.length;

                if (wholePackageSize.readInt32LE(0) <= this.msgSize){
                    this.socket.end();
                    resolve(this.wholePackage.slice(4, this.wholePackage.length));
                }
            });

            this.socket.on('timeout', ()=> {
                this.socket.destroy();
                reject({err:'Error!, server do not respond', func:'request'})
            });

           this.socket.on('error', err => {
                reject({err:err, func:'request'});
            })
        });
    }
}

module.exports = {NetTalk};

I add the link to the GitHub project as well.

\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via edit. Maybe you missed the placeholder on the title element: "State the task that your code accomplishes. Make your title distinctive.". Also from How to Ask: "State what your code does in your title, not your main concerns about it.". \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Jun 27 '18 at 20:03
  • \$\begingroup\$ Thank you so much @SamOnela for your answer I will edit it right now \$\endgroup\$ – Enoc Martinez Jun 27 '18 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.