Search code examples
javascriptmethod-chainingchain

Why is the finallyDecrypt method in this code undefined?


My app receives a base64 encoded value that is also encrypted. The data can come in a few different ways so I wanted to create chain-able methods to keep the code clean and modular.

I want to be able write: decryptionChain.decodeBase64(b64Value).stringToBuffer().finallyDecrypt();

When I run the code, the last property method "finallyDecrypt" returns as undefined.

Why is the "finallyDecrypt" method coming back as undefined? The rest all works and if I run encryptionChain.decodeBase64(b64Value).stringToBuffer() I get back the Buffer I expect. It is only when the finallyDecrypt is chained in that I error out.

Here is the code:

   function decrypt(encrypted) {
    var decipher = crypto.createDecipheriv(algorithm, password, iv);
    decipher.setAuthTag(encrypted.tag);
    var dec = decipher.update(encrypted.content, 'hex', 'utf8');
    dec += decipher.final('utf8');
    return dec;
}

var decryptionChain = {

    currentValue:"",

    decodeBase64: function (encryptedValue){
        this.currentValue = new Buffer(encryptedValue.toString(), "base64");
        return this;
    },

    stringToBuffer: function() {
        if (this.currentValue) {
            myBuffer = JSON.parse(this.currentValue, function (key, value) {
                 return value && value.type === 'Buffer'
                    ? new Buffer(value.data)
                    : value;

            });

        }
        return myBuffer;
    },

    finallyDecrypt : function(myBuffer){
        if(myBuffer){
        decrypt(myBuffer);
        }
        return this;

    }
};

Solution

  • Chaining works by returning this from each method (which points back to the decryptionChain object).

    stringToBuffer, however, returns myBuffer, so you're trying to call a method named finallyDecrypt on that buffer (which doesn't have that method, hence the error).

    If you want it to work with chaining, use something similar to how you're dealing with currentValue:

    stringToBuffer : function() {
      ...
      this.myBuffer = myBuffer;
      return this;
    },
    finallyDecrypt : function() {
      if (this.myBuffer) {
        ...
      }
    }