-
Notifications
You must be signed in to change notification settings - Fork 0
/
treasuryio.js
63 lines (57 loc) · 1.55 KB
/
treasuryio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(function(){
var r
var isNode
if (typeof require !== 'undefined') {
isNode = true
r = require('request')
dsv = require('dsv')
}
var api_endpoint = 'http://api.treasury.io/cc7znvq/47d80ae900e04f2/sql/?q=';
function convertJSONtoCSV (query, format, cb){
fetchJSON(query, function (err, response){
if (err) {
return cb(err)
}
if (format === 'json'){
cb(null, response);
} else if (format === 'csv'){
if (!dsv) {
cb('Please load dsv as a javascript dependency. https://raw.githubusercontent.com/csvsoundsystem/treasuryiojs/master/test/dsv.min.js')
} else {
cb(null, dsv.csv.format(response));
}
}
});
};
function fetchJSON (query, cb) {
var request
if (isNode) {
r(api_endpoint + query, function (err, reponse, body) {
if (err) {
return cb(err)
}
cb(null, JSON.parse(body))
})
} else {
request = new XMLHttpRequest()
request.open('GET', api_endpoint + query, true)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
cb(null, JSON.parse(request.responseText))
} else {
cb(request.status)
}
}
request.onerror = function () {
// There was a connection error of some sort
cb('Error connecting to the API')
}
request.send()
}
}
if (typeof(module) == 'undefined') {
window.treasuryio = convertJSONtoCSV;
} else {
module.exports = convertJSONtoCSV;
}
})()