forked from covidgreen/covid-green-lambdas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcleanup.js
53 lines (40 loc) · 1.54 KB
/
cleanup.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
const SQL = require('@nearform/sql')
const { getDatabase, getExpiryConfig, runIfDev } = require('./utils')
async function createRegistrationMetrics(client) {
const sql = SQL`
INSERT INTO metrics (date, event, os, version, value)
SELECT CURRENT_DATE, 'REGISTER', '', '', COUNT(id)
FROM registrations WHERE created_at::DATE = CURRENT_DATE
ON CONFLICT ON CONSTRAINT metrics_pkey
DO UPDATE SET value = EXCLUDED.value
RETURNING value
`
const { rows } = await client.query(sql)
const [{ value }] = rows
console.log(`updated register metric for today with value ${value}`)
}
async function removeExpiredCodes(client, codeLifetime) {
const sql = SQL`
DELETE FROM verifications
WHERE created_at < CURRENT_TIMESTAMP - ${`${codeLifetime} mins`}::INTERVAL
`
const { rowCount } = await client.query(sql)
console.log(`deleted ${rowCount} codes older than ${codeLifetime} minutes`)
}
async function removeExpiredTokens(client, tokenLifetime) {
const sql = SQL`
DELETE FROM upload_tokens
WHERE created_at < CURRENT_TIMESTAMP - ${`${tokenLifetime} mins`}::INTERVAL
`
const { rowCount } = await client.query(sql)
console.log(`deleted ${rowCount} tokens older than ${tokenLifetime} minutes`)
}
exports.handler = async function() {
const client = await getDatabase()
const { codeLifetime, tokenLifetime } = await getExpiryConfig()
await createRegistrationMetrics(client)
await removeExpiredCodes(client, codeLifetime)
await removeExpiredTokens(client, tokenLifetime)
return true
}
runIfDev(exports.handler)