-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.js
More file actions
160 lines (154 loc) · 4.36 KB
/
Copy pathhandler.js
File metadata and controls
160 lines (154 loc) · 4.36 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
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
const express = require('express')
const cors = require('cors')
const flatten = require('flat')
const { GoogleSpreadsheet } = require('google-spreadsheet')
function atob(str) {
return Buffer.from(str, 'base64').toString()
}
async function spreadsheetAuth(doc, credsClientEmail, credsPrivateKey) {
return await doc.useServiceAccountAuth({
client_email: atob(credsClientEmail),
private_key: atob(credsPrivateKey),
})
}
const write = async (req, res) => {
console.log('Write')
try {
const { row: rowRaw, credsClientEmail, credsPrivateKey, docId } = req.body
if (!docId || !credsClientEmail || !credsPrivateKey) {
console.log('Missing fields')
res.status(400).send({
timestamp: Date.now(),
status: 'not ok',
error: 'Missing required fields',
})
return
}
if (!rowRaw) {
console.log('Write error: no row data')
res.status(400).send({
timestamp: Date.now(),
status: 'not ok',
error: 'Please include data in row property',
})
return
}
console.log('Data to be written exists')
const rowFlat = flatten(rowRaw)
const row = Object.entries(rowFlat).reduce((p, [k, v]) => {
return {
...p,
[k]:
v === null
? ''
: Array.isArray(v)
? v.join(',')
: typeof v === 'object'
? Object.entries(v)
.map(([k, v]) => `${k}: ${v}`)
.join(',')
: v,
}
}, {})
console.log('Flattened data')
const doc = new GoogleSpreadsheet(atob(docId))
console.log('Got doc')
await spreadsheetAuth(doc, credsClientEmail, credsPrivateKey)
console.log('Authenticated')
await doc.loadInfo()
console.log('Loaded info')
const sheet = doc.sheetsByIndex[0]
// empty headers?
// throws if so
console.log('Resolving headers')
try {
await sheet.loadHeaderRow()
} catch (err) {
const hs = Object.keys(row)
await sheet.resize({
rowCount: 3,
columnCount: hs.length,
})
await sheet.setHeaderRow(hs)
}
console.log('Headers in place')
await sheet.loadHeaderRow()
const headers = sheet.headerValues
const newHeaders = Object.keys(row).reduce(
(p, c) => [...p, ...(headers.includes(c) ? [] : [c])],
[],
)
console.log(
`New headers? ${newHeaders.length ? `yes (${newHeaders.length})` : 'no'}`,
)
if (newHeaders.length) {
const rows = await sheet.getRows()
const updatedHeaders = [...headers, ...newHeaders]
await sheet.resize({
rowCount: rows.length + 3,
columnCount: updatedHeaders.length,
})
await sheet.setHeaderRow(updatedHeaders)
console.log('New headers in place')
}
await sheet.addRow(row)
console.log('Row added')
await sheet.saveUpdatedCells()
console.log('Sheet updated')
res.status(200).send({
timestamp: Date.now(),
status: 'ok',
})
} catch (err) {
console.log('Write error:', err)
res.status(400).send({
timestamp: Date.now(),
status: 'not ok',
error: err.message,
})
}
}
const read = async (req, res) => {
console.log('Read')
try {
const { credsClientEmail, credsPrivateKey, docId } = req.query
if (!docId || !credsClientEmail || !credsPrivateKey) {
console.log('Missing fields')
res.status(400).send({
timestamp: Date.now(),
status: 'not ok',
error: 'Missing required fields',
})
return
}
const doc = new GoogleSpreadsheet(atob(docId))
console.log('Got doc')
await spreadsheetAuth(doc, credsClientEmail, credsPrivateKey)
await doc.loadInfo()
const sheet = doc.sheetsByIndex[0]
await sheet.loadCells()
await sheet.loadHeaderRow()
const headers = sheet.headerValues
const rows = await sheet.getRows()
const data = rows.map((row) =>
headers.map((h) => ({ [h]: !!row[h] ? row[h] : '' })),
)
res.status(200).send({
timestamp: Date.now(),
headers,
data,
})
} catch (err) {
console.log('Read error:', err)
res.status(400).send({
timestamp: Date.now(),
status: 'not ok',
error: err.message,
})
}
}
const app = express()
app.post('/', cors(), express.json(), write)
app.get('/', cors(), read)
app.use('*', (req, res) => res.status(405).send('not ok'))
module.exports = app