-
Notifications
You must be signed in to change notification settings - Fork 16
/
CartoDBLoader.js
79 lines (65 loc) · 2.23 KB
/
CartoDBLoader.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import Queue from 'queue-async';
import CartoDBClient from 'cartodb-client';
/*
* Lightweight wrapper around cartodb-client that provides a Promise-based interface
* for making parallel requests to CartoDB given a SQL query and response format for each.
*
* cartodb-client, available via npm, is a simple XHR client tailored for use with CartoDB.
* The functionality here could theoretically be moved into cartodb-client,
* but for now they remain separate and complementary.
*
* @param userId CartoDB user id. Used as the target account for API requests.
* @param apiKey CartoDB API key. If specified, CartoDBLoader will send
* the API key over the wire as a parameter to the GET request to CartoDB.
* Anyone with a web inspector can then see the API key,
* so this should never be used in production!
*/
export default function CartoDBLoader (userId, apiKey, options) {
options = (options) ? options : {};
const cartoDBClient = new CartoDBClient(userId);
/**
* Use `queue-async` to defer() up an array of queries,
* and return a Promise that is resolved when all requests have completed.
* Accepts a list of objects formatted as { query, format }.
*/
function query (queryConfigs) {
return new Promise((resolve, reject) => {
// Run up to 3 requests in parallel
let queue = Queue(3);
queryConfigs.forEach((queryConfig) => {
queue.defer(request, queryConfig);
});
queue.awaitAll((error, ...responses) => {
if (error) {
reject(error);
} else {
resolve(...responses);
}
});
});
}
function request (queryConfig, callback) {
cartoDBClient.sqlRequest(queryConfig.query, function(err, response) {
if (!err) {
let innerResponse;
switch (queryConfig.format.toLowerCase()) {
case 'geojson':
innerResponse = response.features;
break;
default:
innerResponse = response.rows;
break;
}
callback(null, innerResponse);
} else {
callback(err);
}
}, {
'format': queryConfig.format,
'dangerouslyExposedAPIKey': apiKey
});
}
return {
query: query
};
}