-
Notifications
You must be signed in to change notification settings - Fork 3
/
DataStore.js
74 lines (65 loc) · 2.19 KB
/
DataStore.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
import CKANApi from 'lib/CKANApi';
/**
* Represents a "data store" on CKAN. Can be considered essentially an API to a CSV containing
* columns (fields) and rows (records) of data.
*/
export default class {
constructor(endpoint, resource) {
this.endpoint = endpoint;
this.resource = resource;
}
/**
* Perform a "datastore_search" action on the CKAN resource
*
* @param {string[]} fields - The fields to return for each record
* @param {string|object} term - A string term to search globally or an object of field : term
* @param {boolean} distinct
* @param {number} limit
* @param {number} offset
* @return {Promise}
*/
search(fields, term = null, distinct = false, limit = 100, offset = 0) {
if (!Array.isArray(fields) || !fields.length) {
return Promise.reject(false);
}
const options = {
id: this.resource,
fields: fields.map(encodeURIComponent).join(','),
// Always ensure a total is requested
include_total: true,
};
// If an invalid term is given then assume that it will return nothing
const termType = term === null ? null : typeof term;
if (term !== null && termType !== 'string' && termType !== 'object') {
return Promise.resolve(false);
}
// Parse the term - which can be a global term (string) or an object of { field: term }.
if (termType === 'string' && term.length) {
options.q = term;
} else if (termType === 'object') {
const terms = Object.entries(term);
if (terms.length) {
// Nicely enough the expected format in this case is JSON :tada:
options.q = JSON.stringify(term);
}
}
// Add the distinct, limit and offset vars if requested
if (distinct) {
options.distinct = true;
}
options.limit = limit;
options.offset = offset;
// Make the request and parse the result into a more usable format
return CKANApi.makeRequest(this.endpoint, 'datastore_search', options).then(
response => response.json().then(result => {
if (!result.success) {
return false;
}
return {
records: result.result.records,
total: result.result.total,
};
})
);
}
}