Last active
August 30, 2024 21:23
-
-
Save azhuravlov/102ed3502a91d001745948d7f784477f to your computer and use it in GitHub Desktop.
Emercoin + NodeJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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); | |
| } | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example below: