Skip to content

Instantly share code, notes, and snippets.

@azhuravlov
Last active August 30, 2024 21:23
Show Gist options
  • Select an option

  • Save azhuravlov/102ed3502a91d001745948d7f784477f to your computer and use it in GitHub Desktop.

Select an option

Save azhuravlov/102ed3502a91d001745948d7f784477f to your computer and use it in GitHub Desktop.
Emercoin + NodeJS
'use strict';
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
function Connection(username, password, hostname, port, protocol) {
let _this = this;
_this.username = username;
_this.password = password;
_this.hostname = hostname ? hostname : '127.0.0.1';
_this.port = port ? port : 6662;
_this.protocol = protocol ? protocol : 'https';
if (!(_this.protocol === 'https' || _this.protocol === 'http')) {
throw new Error('Unsupported protocol, must be "https" or "http" used.');
}
_this.options = {
host: _this.hostname,
port: _this.port,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept-Charset': 'utf-8;q=0.7,*;q=0.7',
},
auth: _this.username + ':' + _this.password,
timeout: 1000
};
this.query = function(method, parameters) {
if (!(parameters === undefined || Array.isArray(parameters) || typeof parameters === 'string')) {
throw new Error('Unexpected parameter type given.');
}
let data = {};
data.method = method;
if (typeof parameters === 'string' || parameters instanceof String) {
data.params = [parameters];
}
data = JSON.stringify(data);
_this.options.headers['Content-Length'] = data.length;
return new Promise(function(resolve, reject) {
let request = require(_this.protocol).request(_this.options, function(res) {
let raw = '';
res.on('data', function(ch) {
raw += ch;
});
res.on('end', function() {
let data = JSON.parse(raw);
if (data.error) {
reject(data.error);
} else {
resolve(data.result);
}
});
});
request.on('error', (e) => {
console.error(`Problem with request: ${e.message}`);
reject(e);
});
request.write(data);
request.end();
});
}
}
module.exports = {
createConnection: function(username, password, hostname, port, protocol) {
return new Connection(username, password, hostname, port, protocol);
}
};
@azhuravlov
Copy link
Author

Usage example below:

'use strict';

let emercoin = require('./emercoin').createConnection('username', 'userpass', '192.168.0.1');

emercoin.query('getinfo')
    .then(function(data) {
        console.log("\n", 'Wallet version: ', data.version);
    })
    .catch(function(e) {
        console.log("\n", 'We have error: ', e.message);
    });

emercoin.query('name_show', 'ssh:sv')
    .then(function(data){
        console.log("\n", data);
    })
    .catch(function(e){
        console.log("\n", 'We have error: ', e.message);
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment