-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
246 lines (201 loc) · 7.33 KB
/
Copy pathserver.ts
File metadata and controls
246 lines (201 loc) · 7.33 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
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
import https from 'https'
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import { JWT, JWTOptions } from 'google-auth-library'
import { GoogleSpreadsheet } from 'google-spreadsheet';
const app = express();
https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/
app.use(cors({
// origin: 'https://www.section.io'
// origin: '*'
origin: ['http://localhost:3456', "https://vite-production-bb5a.up.railway.app"],
maxAge: 600, // Access-Control-Max-Age is 600 ~ https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it
}));
app.get('/', (req, res) =>{
res.send("hello expressnecks server! potato");
});
app.get('/ping', (req, res) =>{
res.send("pong");
});
app.get('/env/hosted', (req, res) =>{
const hostedBy = process.env.RNSERVER_HOSTED || "localdev"
const hostLive = process.env.RNSERVER_HOSTED == 'live'
res.send(hostedBy);
});
app.get('/najft', (req, res) => {
const url = "https://www.jftna.org/jft/"
const data:string[] = []
https.get(url, lalala => {
console.log("got response" + lalala.statusCode)
lalala.on('data', chunk => {
data.push(chunk)
}).on('end', () => {
const str = data.join('')
const startToken = "<body>"
const endToken = "</body>"
const start = str.indexOf(startToken)
const end = str.indexOf(endToken)
if ((start !== -1) && (end !== -1)) {
const body = str.substring(start + startToken.length, end)
res.send(body)
} else {
res.send(str)
}
})
})
})
// app.use(express.json())
// // app.use(express.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.text())
let banner: string = "default banner"
app.get('/messages/banner', (req, res) =>{
res.send(banner);
});
app.post('/messages/banner', (req, res) =>{
// let data = ''
// req.on('data', chunk => data += chunk).on('end', () => {
// console.log('setting message banner', data)
// banner = data
// res.status(200)
// res.end()
// })
console.log('req.body', req.body)
banner = req.body
res.end()
});
let volatile: any = {serverValue: 'initial'}
app.get('/volatile', (req, res) =>{
res.send({
...volatile,
server: {
retreived: new Date()
}
});
});
app.post('/volatile/:path', (req, res) =>{
// let data = ''
// req.on('data', chunk => data += chunk).on('end', () => {
// console.log('setting message banner', data)
// banner = data
// res.status(200)
// res.end()
// })
// console.log('req.params.path', req.params.path)
// console.log('req.body=')
// console.log(' ', req.body)
if ((req.body) && (typeof req.body === 'object') && (Object.entries(req.body).length === 0)) {
// client sent us undefined
delete volatile[req.params.path]
} else {
// everything else come as {value: ___ } because
// otherwise we crash on null and numbers and other things
volatile[req.params.path] = req.body
}
res.end()
});
const jwtOptions: JWTOptions = {
// env var values here are copied from service account credentials generated by google
// see "Authentication" section in docs for more info
email: process.env.RNSERVER_GOOGLE_EMAIL,
key: process.env.RNSERVER_GOOGLE_KEY,
scopes: [
'https://www.googleapis.com/auth/spreadsheets',
],
}
app.get('/sheets/auth', async (req, res) =>{
res.send(jwtOptions)
});
const sheetApi = {
getSheet: async function (spreadSheetId: string, sheetNameOrIndex: string) {
const serviceAccountAuth = new JWT(jwtOptions);
const doc = new GoogleSpreadsheet(spreadSheetId, serviceAccountAuth);
await doc.loadInfo()
const sheetIndex = parseInt(sheetNameOrIndex)
const sheet =
!isNaN(sheetIndex)
? doc.sheetsByIndex[sheetIndex]
: doc.sheetsByTitle[sheetNameOrIndex]
return {doc, sheet}
}
}
app.get('/sheet/:spreadSheetId/:sheetNameOrIndex', async (req, res) =>{
console.log('sheets!')
try {
const {doc, sheet} = await sheetApi.getSheet(req.params.spreadSheetId, req.params.sheetNameOrIndex)
const minCount = 1000 // even on a blank sheet, google says there are a 1000 records
const rows = await sheet.getRows({offset: Math.max(0, sheet.rowCount - minCount), limit: minCount})
const limit = 200 //idk weight doesnt need lots but for roughnecks links we already past 20, so, whatevers good luck future me
rows.splice(0, Math.max(0, rows.length - limit))
const data = {
docTitle: doc.title,
sheetTitle: sheet.title,
rowCount: sheet.rowCount,
rowLength: rows.length,
headerValues: sheet.headerValues,
rows: rows.map(
row => sheet.headerValues.reduce(
(acc, cur) => ({...acc, [cur]: row.get(cur)}),
{})
),
}
console.log(data)
res.send(data);
} catch (e) {
console.error(e)
res.status(500)
res.send(e)
}
res.end()
});
app.post('/sheet/:spreadSheetId/:sheetNameOrIndex', async (req, res) =>{
console.log('sheets! incoming')
try {
console.log('req.body', req.body)
const {doc, sheet} = await sheetApi.getSheet(req.params.spreadSheetId, req.params.sheetNameOrIndex)
await sheet.addRow(req.body)
} catch (e) {
console.error(e)
res.status(500)
res.send(e)
}
res.end()
});
app.post('/sheet/:spreadSheetId/:sheetNameOrIndex/pk', async (req, res) =>{
console.log('sheets! incoming')
try {
console.log('req.body', req.body)
const {doc, sheet} = await sheetApi.getSheet(req.params.spreadSheetId, req.params.sheetNameOrIndex)
const minCount = 1000 // even on a blank sheet, google says there are a 1000 records
const rows = await sheet.getRows({offset: Math.max(0, sheet.rowCount - minCount), limit: minCount})
const firstColumn = sheet.headerValues[0]
if (!firstColumn) {
throw "no primary key column defined"
}
const updateValues = req.body
const pk = updateValues[firstColumn]
const existing = rows.find(row => row.get(firstColumn) == pk)
if (!existing) {
await sheet.addRow(req.body)
} else {
console.log('found', existing)
console.log('assigning', updateValues)
Object.entries(updateValues).forEach(([key,value]) => {
if (value === undefined) return
existing.set(key, value??'')
})
// existing.assign(updateValues)
await existing.save()
}
} catch (e) {
console.error(e)
res.status(500)
res.send(e)
}
res.end()
});
const desiredPort = process.env.PORT;
const port = desiredPort || 6543
app.listen(port, () => console.log(`application started on port ${port} (desired was ${desiredPort})`))