Add some standard methods to Message

This adds `fromString`, `fromJSON`, `toObject`, `toJSON`, `toString`,
and `inspect` to Message. These methods are trivial since Message only
contains a string message, but they should probably be added for
consistency.

Should toBuffer/fromBuffer be added as well?
This commit is contained in:
Trevin Hofmann 2015-02-08 03:00:30 -06:00
parent 054aabfada
commit b5093878ab
1 changed files with 58 additions and 1 deletions

View File

@ -8,6 +8,7 @@ var BufferWriter = bitcore.encoding.BufferWriter;
var ECDSA = bitcore.crypto.ECDSA;
var Signature = bitcore.crypto.Signature;
var sha256sha256 = bitcore.crypto.Hash.sha256sha256;
var JSUtil = bitcore.util.js;
/**
* Will construct a new message to sign and verify.
@ -107,5 +108,61 @@ Message.prototype.verify = function verify(bitcoinAddress, signatureString) {
return this._verify(publicKey, signature);
};
module.exports = Message;
/**
* Instantiate a message from a message string
*
* @param {String} str - A string of the message
* @returns {Message} A new instance of a Message
*/
Message.fromString = function(str) {
return new Message(str);
};
/**
* Instantiate a message from JSON
*
* @param {String} json - An JSON string or Object with keys: message
* @returns {Message} A new instance of a Message
*/
Message.fromJSON = function fromJSON(json) {
if (JSUtil.isValidJSON(json)) {
json = JSON.parse(json);
}
return new Message(json.message);
};
/**
* @returns {Object} A plain object with the message information
*/
Message.prototype.toObject = function toObject() {
return {
message: this.message
};
};
/**
* @returns {String} A JSON representation of the message information
*/
Message.prototype.toJSON = function toJSON() {
return JSON.stringify(this.toObject());
};
/**
* Will return a the string representation of the message
*
* @returns {String} Message
*/
Message.prototype.toString = function() {
return this.message;
};
/**
* Will return a string formatted for the console
*
* @returns {String} Message
*/
Message.prototype.inspect = function() {
return '<Message: ' + this.toString() + '>';
};
module.exports = Message;