This repository has been archived by the owner on Jun 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
75 lines (58 loc) · 2.17 KB
/
index.ts
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
import * as cors from 'cors'
import { getFormSubmissions } from 'dappform-forms-api'
import * as express from 'express'
import { Request, Response } from 'express'
import { getFile, putFile } from 'dappform-forms-api/dist/lib/write'
const wt = require('webtask-tools')
const loadBlockstack = require('blockstack-anywhere')
function initBlockstack(context: any) {
console.assert(context.secrets.BLOCKSTACK, "missing BLOCKSTACK")
console.assert(context.secrets.BLOCKSTACK_GAIA_HUB_CONFIG, "missing BLOCKSTACK_GAIA_HUB_CONFIG")
console.assert(context.secrets.BLOCKSTACK_TRANSIT_PRIVATE_KEY, "missing BLOCKSTACK_TRANSIT_PRIVATE_KEY")
process.env.BLOCKSTACK = context.secrets.BLOCKSTACK
process.env.BLOCKSTACK_GAIA_HUB_CONFIG = context.secrets.BLOCKSTACK_GAIA_HUB_CONFIG
process.env.BLOCKSTACK_TRANSIT_PRIVATE_KEY = context.secrets.BLOCKSTACK_TRANSIT_PRIVATE_KEY
loadBlockstack()
}
const app = express()
app.use(cors())
app.get('/version', (req:any, res) => res.send(req.webtaskContext.secrets.version || "0.0.0"))
interface WtReq extends Request {
webtaskContext: Object,
}
app.post('/:formUuid', async (req: WtReq, res:Response) => {
const formUuid = req.params.formUuid
console.assert(formUuid, "Didn't find form id")
initBlockstack(req.webtaskContext)
const statsFile = `views/${formUuid}.json`
type FormStats = {
numViews: number
numSubmissions: number
}
let viewsObj:FormStats = await getFile(statsFile) as any
if (!viewsObj) {
viewsObj = <FormStats>{
numViews: 0,
}
}
viewsObj.numViews += 1
const submissions = await getFormSubmissions(formUuid)
console.log('subs to form '+formUuid)
console.log(submissions[formUuid])
const numSubmissions = submissions[formUuid] ? Object.values( submissions[formUuid] ).length : 0
viewsObj.numSubmissions = numSubmissions
try {
await putFile(statsFile, viewsObj) // will encrypt file
console.log("wrote "+statsFile, viewsObj)
}
catch (e) {
console.error(e)
return res.sendStatus(500)
}
res.sendStatus(202)
})
module.exports = wt.fromExpress(app)
// app.listen(3000, ()=> {
// simpleWebhook("http://localhost:3000",{"data": {}})
// console.debug('listening on 3000')
// })