-
Notifications
You must be signed in to change notification settings - Fork 46
/
makeTable.js
64 lines (57 loc) · 1.94 KB
/
makeTable.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
var request = require('request')
var csv = require('binary-csv')
var concat = require('concat-stream')
var parser = require('google-spreadsheets-key-parser')
var markdownify = require('to-markdown')
var fs = require('fs')
module.exports = function makeTable (fullURL, callback) {
var csvParser = csv({json: true})
if (!fullURL.match('http')) {
// using a local file for testing
var csvFile = fs.createReadStream(fullURL)
return csvFile.pipe(csvParser).pipe(concat(rows))
}
var newBase = 'https://docs.google.com/spreadsheets/d/'
var newQuery = '/export?gid=0&format=csv'
var oldBase = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key='
var oldQuery = '&single=true&gid=0&output=csv'
var formattedURL = ''
var parsed = parser(fullURL)
// returns:
// { key: '',
// isNewSheets: true }
if (parsed.isNewSheets) {
formattedURL = newBase + parsed.key + newQuery
} else {
formattedURL = oldBase + parsed.key + oldQuery
}
var req = request(formattedURL)
req.on('response', function (response) {
if (response.statusCode.toString() === '404') {
return callback(new Error('HI Spreadsheet not found.\n' +
'Please double check your spreadsheet key is correct.'))
}
if (response.req._header.match('ServiceLogin?')) {
return callback(new Error('Cannot access spreadsheet.\n' +
'Be sure you "Publish to the Web" and turn the share settings to public on your spreadsheet.'))
}
req.pipe(csvParser).pipe(concat(rows))
})
function rows (data) {
var table = '|'
var headers = Object.keys(data[0])
var underHeaders = ''
headers.map(function (key) {
table += key + '|'
underHeaders += ' ------ |'
})
table += '\n|' + underHeaders + '\n'
data.map(function (row) {
var values = headers.map(function (h) {
return markdownify(row[h])
})
table += '|' + values.join('|') + '|\n'
})
return callback(null, table)
}
}