forked from ProtoSchool/protoschool.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsheets.js
More file actions
59 lines (49 loc) · 2 KB
/
Copy pathsheets.js
File metadata and controls
59 lines (49 loc) · 2 KB
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
/*
Google Sheets API helpers
*/
const promisify = require('util').promisify
const { google } = require('googleapis')
const googleAuth = require('./auth')
const sheets = google.sheets({ version: 'v4', auth: googleAuth })
/*
Fetch data from a spreadsheet
*/
exports.getSpreadSheet = promisify(sheets.spreadsheets.values.get).bind(sheets.spreadsheets.values)
/*
Transforms a spreadsheet into a usable data structure.
rows: raw rows from the spreadsheet (spreadsheet.data.values)
columns:
- list of columns strings to be used as property names
- or list of pair {key: string, value: fn}
- key: string to be used as property name
- fn(row: Object): transform function to be ran on this column
extraColumns: extra columns to be added to the row object. list of pair {key: string, value: fn}:
- key: string to be used as property name
- fn(row: Object): transform function to be ran on this column
*/
exports.transformSpreadSheet = (rows, columns, extraColumns = []) => (
rows
// transform each row array into a row object using the columns as keys
.map(row => row.reduce((mappedRow, value, index) => ({
...mappedRow,
[typeof columns[index] === 'string' ? columns[index] : columns[index].key]: value
}), {}))
// run the transform function on each property of each row, if any
.map((rowObject, index) => {
let transformedRowObject = {}
for (const key in rowObject) {
const transformer = columns.find(column => column === key || column.key === key).transform ||
((values, key) => values[key])
transformedRowObject[key] = transformer(rowObject, key)
}
// add the extra columns
return {
id: index + 1,
...transformedRowObject,
...extraColumns.reduce((rowObjectWithNewProperties, extraColumn) => ({
...rowObjectWithNewProperties,
[extraColumn.key]: extraColumn.value(rowObject, transformedRowObject)
}), {})
}
})
)