UNPKG

2.28 kBJavaScriptView Raw
1var request = require("request"),
2 querystring = require("querystring"),
3 CSV = require("csv-string");
4
5/**
6 * The client for bitcoincharts.com API.
7 *
8 * @constructor
9 */
10var BitcoinCharts = function() {
11 this.url = "http://bitcoincharts.com/t/";
12};
13
14/**
15 * Private helper method for making API requests.
16 *
17 * @param {string} baseUrl The base URL for the request.
18 * @param {string} method The API endpoint the request will call.
19 * @param {!Object} params The query parameters to use for the request.
20 * @param {function(string)} parserLambda The function to use for parsing the response into an easy to use format.
21 * @param {function(Error, Object)} callback The callback to call with an error or the result.
22
23 */
24var makeRequest = function(baseUrl, method, params, parserLambda, callback) {
25 var queryString = querystring.stringify(params),
26 url = baseUrl + method;
27
28 if (queryString) {
29 url += "?" + queryString;
30 }
31
32 request(url, function(err, response, body) {
33 if(err || response.statusCode !== 200) {
34 return callback(new Error(err ? err : response.statusCode));
35 }
36
37 var result;
38 try {
39 result = parserLambda(body);
40 } catch(error) {
41 return callback(new Error(error));
42 }
43
44 callback(null, result);
45 });
46};
47
48/**
49 * Call the 'weighted_prices.json' endpoint of the API.
50 *
51 * @param {function(Error, Object)} callback The callback to call with an error or the result.
52 */
53
54BitcoinCharts.prototype.weightedPrices = function(callback) {
55 makeRequest(this.url, "weighted_prices.json", {}, JSON.parse, callback);
56};
57
58/**
59 * Call the 'markets.json' endpoint of the API.
60 *
61 * @param {function(Error, Object)} callback The callback to call with an error or the result.
62 */
63BitcoinCharts.prototype.markets = function(callback) {
64 makeRequest(this.url, "markets.json", {}, JSON.parse, callback);
65};
66
67/**
68 * Call the 'trades.csv' endpoint of the API.
69 *
70 * @param {!Object} params An object containing at least the 'symbol' to use and optional an 'end' time.
71 * @param {function(Error, Array)} callback The callback to call with an error or the result.
72 */
73BitcoinCharts.prototype.trades = function(params, callback) {
74 makeRequest(this.url, "trades.csv", params, CSV.parse, callback);
75};
76
77module.exports = BitcoinCharts;