forked from 55sketch/gsx2json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
62 lines (60 loc) · 1.94 KB
/
api.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
var request = require('request');
module.exports = function(req, res, next) {
var id = req.query.id,
sheet = req.query.sheet || 1,
query = req.query.q || '',
useIntegers = req.query.integers || true,
showRows = req.query.rows || true,
showColumns = req.query.columns || true,
url = 'https://spreadsheets.google.com/feeds/list/' + id + '/' + sheet + '/public/values?alt=json';
request(url, function(error, response, body) {
if(!error && response.statusCode === 200) {
var data = JSON.parse(response.body);
var responseObj = {};
var rows = [];
var columns = {};
for(var i = 0; i < data.feed.entry.length; i++) {
var entry = data.feed.entry[i];
var keys = Object.keys(entry);
var newRow = {};
var queried = false;
for(var j = 0; j < keys.length; j++) {
var gsxCheck = keys[j].indexOf('gsx$');
if(gsxCheck > -1) {
var key = keys[j];
var name = key.substring(4);
var content = entry[key];
var value = content.$t;
if(value.toLowerCase().indexOf(query.toLowerCase()) > -1) {
queried = true;
}
if(useIntegers === true && !isNaN(value)) {
value = Number(value);
}
newRow[name] = value;
if(queried === true) {
if(!columns.hasOwnProperty(name)) {
columns[name] = [];
columns[name].push(value);
} else {
columns[name].push(value);
}
}
}
}
if(queried === true) {
rows.push(newRow);
}
}
if(showColumns === true) {
responseObj['columns'] = columns;
}
if(showRows === true) {
responseObj['rows'] = rows;
}
return res.status(200).json(responseObj);
} else {
return res.status(response.statusCode).json(error);
}
});
};