-
Notifications
You must be signed in to change notification settings - Fork 33
/
helper.js
executable file
·386 lines (275 loc) · 11.1 KB
/
helper.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
var fs = require('fs')
var GoogleSpreadsheet = require('google-spreadsheet')
var Promise = require('bluebird')
// constants used for converting column names into number/index
var ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
var ALPHABET_BASE = ALPHABET.length
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function getWords(phrase) {
return phrase.replace(/[- ]/ig, ' ').split(' ')
}
// Service Account credentials are first parsed as JSON and, in case this fails,
// they are considered a file path
function parseServiceAccountCredentials(credentials) {
if (typeof credentials === 'string') {
try {
return JSON.parse(credentials)
} catch(ex) {
return JSON.parse(fs.readFileSync(credentials, 'utf8'))
}
}
return credentials
}
function handlePropertyName(cellValue, handleMode) {
var handleModeType = typeof handleMode
if (handleModeType === 'function')
return handleMode(cellValue)
var propertyName = (cellValue || '').trim()
if (handleMode === 'camel' || handleModeType === 'undefined')
return getWords(propertyName.toLowerCase()).map(function(word, index) {
return !index ? word : capitalize(word)
}).join('')
if (handleMode === 'pascal')
return getWords(propertyName.toLowerCase()).map(function(word) {
return capitalize(word)
}).join('')
if (handleMode === 'nospace')
return getWords(propertyName).join('')
return propertyName
}
function handleIntValue(val) {
return parseInt(val, 10) || 0
}
// returns a number if the string can be parsed as an integer
function handlePossibleIntValue(val) {
if (typeof val === 'string' && /^\d+$/.test(val))
return handleIntValue(val)
return val
}
function normalizePossibleIntList(option, defaultValue) {
return normalizeList(option, defaultValue).map(handlePossibleIntValue)
}
// should always return an array
function normalizeList(option, defaultValue) {
if (typeof option === 'undefined')
return defaultValue || []
return Array.isArray(option) ? option : [option]
}
function setPropertyTree(object, tree, value) {
if (!Array.isArray(tree))
tree = [tree]
var prop = tree[0]
if (!prop)
return
object[prop] = tree.length === 1 ? value : (typeof object[prop] === 'object' ? object[prop] : {})
setPropertyTree(object[prop], tree.slice(1), value)
}
function parseColIdentifier(col) {
var colType = typeof col
if (colType === 'string') {
return col.trim().replace(/[ \.]/i, '').toLowerCase().split('').reverse().reduce(function(totalValue, letter, index) {
var alphaIndex = ALPHABET.indexOf(letter)
if (alphaIndex === -1)
throw new Error('Column identifier format is invalid')
var value = alphaIndex + 1
return totalValue + value * Math.pow(ALPHABET_BASE, index)
}, 0)
}
if (colType !== 'number')
throw new Error('Column identifier value type is invalid')
return col
}
function cellIsValid(cell) {
return !!cell && typeof cell.value === 'string' && cell.value !== ''
}
// google spreadsheet cells into json
exports.cellsToJson = function(allCells, options) {
// setting up some options, such as defining if the data is horizontal or vertical
options = options || {}
var rowProp = options.vertical ? 'col' : 'row'
var colProp = options.vertical ? 'row' : 'col'
var isHashed = options.hash && !options.listOnly
var includeHeaderAsValue = options.listOnly && options.includeHeader
var headerStartNumber = options.headerStart ? parseColIdentifier(options.headerStart) : 0
var headerSize = Math.min(handleIntValue(options.headerSize)) || 1
var ignoredRows = normalizePossibleIntList(options.ignoreRow)
var ignoredCols = normalizePossibleIntList(options.ignoreCol).map(parseColIdentifier)
var ignoredDataNumbers = options.vertical ? ignoredRows : ignoredCols
ignoredDataNumbers.sort().reverse()
var maxCol = 0
// organizing (and ordering) the cells into arrays
var rows = []
allCells.forEach(function(cell) {
if (ignoredRows.indexOf(cell.row) !== -1 || ignoredCols.indexOf(cell.col) !== -1)
return
maxCol = Math.max(maxCol, cell[colProp])
var rowIndex = cell[rowProp] - 1
if (typeof rows[rowIndex] === 'undefined')
rows[rowIndex] = []
rows[rowIndex].push(cell)
})
rows.forEach(function(col) {
col.sort(function(cell1, cell2) {
return cell1[colProp] - cell2[colProp]
})
})
// find the first row with data (or the specified header start line) to use it as property names
for (var firstRowIndex = 0; firstRowIndex < rows.length; firstRowIndex++) {
var cells = rows[firstRowIndex]
if (!cells)
continue
if (headerStartNumber && headerStartNumber !== cells[0][rowProp])
continue
break
}
var properties
if (!options.listOnly) {
// creating the property names map (to detect the name by index),
// considering the header size
properties = {}
var headerEndRowIndex = firstRowIndex + headerSize - 1
var headerRows = rows.filter(function(row, index) {
return index >= firstRowIndex && index <= headerEndRowIndex
}).reverse()
for (var colNumber = 1; colNumber <= maxCol; colNumber++) {
var foundFirstCell = false
var propertyMap = headerRows.map(function (row, index) {
var headerCell = row.filter(function(cell) {
return cell[colProp] === colNumber
})[0]
if (!foundFirstCell && cellIsValid(headerCell))
foundFirstCell = true
// the first header cell (from the bottom to top) must be from this column,
// so we don't check to the left
else if (foundFirstCell && !cellIsValid(headerCell)) {
// finding the nearest filled cell to the left
headerCell = row.filter(function(cell) {
return cell[colProp] < colNumber
}).reverse()[0]
if (cellIsValid(headerCell)) {
// then we check if the cell found has other filled cells below,
// and ignore it if not
var hasCellBelow = headerRows.filter(function (r, i) {
return i === index - 1
}).some(function(r) {
return cellIsValid(r.filter(function(cell) {
return cell[colProp] === headerCell[colProp]
})[0])
})
if (!hasCellBelow)
headerCell = null
}
}
return headerCell
}).map(function(cell) {
if (!cellIsValid(cell))
return
return handlePropertyName(cell.value, options.propertyMode)
}).filter(function(n) {
return n
}).reverse()
if (propertyMap.length)
properties[colNumber] = propertyMap
}
}
// removing (or not) the first rows, before and including the ones that is used as header
if (!includeHeaderAsValue)
rows.splice(0, firstRowIndex + headerSize)
// iterating through remaining row to fetch the values and build the final data object
var finalList = isHashed ? {} : []
rows.forEach(function(cells) {
var newObject = options.listOnly ? [] : {}
var hasValues = false
cells.forEach(function(cell) {
var val
var colNumber = cell[colProp]
if (properties && !properties[colNumber])
return
if (typeof cell.numericValue !== 'undefined') {
val = parseFloat(cell.numericValue)
hasValues = true
} else if (cell.value === 'TRUE') {
val = true
hasValues = true
} else if (cell.value === 'FALSE') {
val = false
hasValues = true
} else if (cell.value !== '' && typeof cell.value !== 'undefined') {
val = cell.value
hasValues = true
}
if (options.listOnly) {
newObject[colNumber - 1] = val
} else {
setPropertyTree(newObject, properties[colNumber], val)
}
})
if (hasValues) {
if (options.listOnly) {
// this is guaranteed because the list is sorted as needed
ignoredDataNumbers.forEach(function(number) {
newObject.splice(number - 1, 1)
})
}
if (isHashed) {
finalList[newObject[options.hash]] = newObject
} else {
finalList.push(newObject)
}
}
})
return finalList
}
exports.getWorksheets = function(options) {
return Promise.try(function() {
var spreadsheet = Promise.promisifyAll(new GoogleSpreadsheet(options.spreadsheetId))
if (options.credentials)
return spreadsheet.useServiceAccountAuthAsync(parseServiceAccountCredentials(options.credentials)).return(spreadsheet)
if (options.token) {
spreadsheet.setAuthToken({
value: options.token,
type: options.tokentype || 'Bearer'
})
}
return spreadsheet
})
.then(function(spreadsheet) {
return spreadsheet.getInfoAsync()
})
.then(function(sheetInfo) {
return sheetInfo.worksheets.map(function(worksheet) {
return Promise.promisifyAll(worksheet)
})
})
}
exports.spreadsheetToJson = function(options) {
var allWorksheets = !!options.allWorksheets
var expectMultipleWorksheets = allWorksheets || Array.isArray(options.worksheet)
return exports.getWorksheets(options)
.then(function(worksheets) {
if (allWorksheets)
return worksheets
var identifiers = normalizePossibleIntList(options.worksheet, [0])
var selectedWorksheets = worksheets.filter(function(worksheet, index) {
return identifiers.indexOf(index) !== -1 || identifiers.indexOf(worksheet.title) !== -1
})
if (!expectMultipleWorksheets)
selectedWorksheets = selectedWorksheets.slice(0, 1)
if (selectedWorksheets.length === 0)
throw new Error('No worksheet found!')
return selectedWorksheets
})
.then(function(worksheets) {
return Promise.all(worksheets.map(function(worksheet) {
return worksheet.getCellsAsync()
}))
})
.then(function(results) {
var finalList = results.map(function(allCells) {
return exports.cellsToJson(allCells, options)
})
return expectMultipleWorksheets ? finalList : finalList[0]
})
}