1 | var request = require('request');
|
2 |
|
3 | function resultHandler(cb) {
|
4 | return function (err, resp, body) {
|
5 | if (err) {
|
6 | cb("Request error: " + err);
|
7 | } else if (resp.statusCode != 200) {
|
8 | var msg = "Unexpected status code: " + resp.statusCode;
|
9 | if (body.error) {
|
10 | msg += ", ";
|
11 | msg += body.error;
|
12 | }
|
13 | cb(msg);
|
14 | } else {
|
15 | if (!body.success) {
|
16 | cb("Server error: " + (body.error || body.message));
|
17 | } else {
|
18 | cb(null, body);
|
19 | }
|
20 | }
|
21 | }
|
22 | }
|
23 |
|
24 | function Api(options) {
|
25 | this.options = options || {};
|
26 | this.mainnet = this.options.mainnet;
|
27 | this.host = this.options.host || "127.0.0.1";
|
28 | this.port = this.options.port || (this.mainnet ? 8192 : 4096);
|
29 | this.baseUrl = "http://" + this.host + ":" + this.port;
|
30 | this.magic = this.mainnet ? '5f5b3cf5' : '594fe0f3';
|
31 | }
|
32 |
|
33 | Api.prototype.get = function (path, params, cb) {
|
34 | var qs = null;
|
35 | if (typeof params === 'function') {
|
36 | cb = params;
|
37 | } else {
|
38 | qs = params;
|
39 | }
|
40 | request({
|
41 | method: "GET",
|
42 | url: this.baseUrl + path,
|
43 | json: true,
|
44 | qs: qs
|
45 | }, resultHandler(cb));
|
46 | }
|
47 |
|
48 | Api.prototype.put = function (path, data, cb) {
|
49 | request({
|
50 | method: "PUT",
|
51 | url: this.baseUrl + path,
|
52 | json: data
|
53 | }, resultHandler(cb));
|
54 | }
|
55 |
|
56 | Api.prototype.post = function (path, data, cb) {
|
57 | request({
|
58 | method: "POST",
|
59 | url: this.baseUrl + path,
|
60 | json: data
|
61 | }, resultHandler(cb));
|
62 | }
|
63 |
|
64 | Api.prototype.broadcastTransaction = function (trs, cb) {
|
65 | request({
|
66 | method: "POST",
|
67 | url: this.baseUrl + "/peer/transactions",
|
68 |
|
69 | headers: {
|
70 | magic: this.magic,
|
71 | version: ""
|
72 | },
|
73 | json: {
|
74 | transaction: trs
|
75 | }
|
76 | }, resultHandler(cb));
|
77 | }
|
78 |
|
79 | module.exports = Api;
|