Skip to content

Commit 3ea2ac2

Browse files
committed
Add script for showing stats summary
1 parent c0e8d77 commit 3ea2ac2

1 file changed

Lines changed: 88 additions & 0 deletions

File tree

scripts/show-stats.js

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const redis = require('redis')
2+
const subDays = require('date-fns/sub_days')
3+
const prettyBytes = require('pretty-bytes')
4+
const invariant = require('invariant')
5+
6+
const RedisURL = process.env.REDIS_URL
7+
8+
invariant(
9+
RedisURL,
10+
'Missing the $REDIS_URL environment variable'
11+
)
12+
13+
const db = redis.createClient(RedisURL)
14+
15+
const getKeyValues = (keys) =>
16+
new Promise((resolve, reject) => {
17+
db.mget(keys, (error, values) => {
18+
if (error) {
19+
reject(error)
20+
} else {
21+
resolve(values)
22+
}
23+
})
24+
})
25+
26+
const sumKeys = (keys) => getKeyValues(keys).then(sumValues)
27+
28+
const createRange = (start, end) => {
29+
const range = []
30+
31+
while (start < end)
32+
range.push(start++)
33+
34+
return range
35+
}
36+
37+
const createDayKey = (date) =>
38+
`${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`
39+
40+
const createHourKey = (date) =>
41+
`${createDayKey(date)}-${date.getUTCHours()}`
42+
43+
const sumValues = (array) =>
44+
array.reduce((memo, n) => memo + (parseInt(n, 10) || 0), 0)
45+
46+
const now = new Date
47+
48+
const createPastDays = (n) =>
49+
createRange(1, n + 1).map(days => subDays(now, days)).reverse()
50+
51+
const pastSevenDays = createPastDays(7)
52+
const pastThirtyDays = createPastDays(30)
53+
54+
sumKeys(
55+
pastSevenDays.map(date => `stats-requests-${createHourKey(date)}`)
56+
).then(total => {
57+
console.log(
58+
'Requests this week: %s',
59+
total.toLocaleString()
60+
)
61+
})
62+
63+
sumKeys(
64+
pastSevenDays.map(date => `stats-bandwidth-${createHourKey(date)}`)
65+
).then(total => {
66+
console.log(
67+
'Bandwidth this week: %s',
68+
prettyBytes(total)
69+
)
70+
})
71+
72+
sumKeys(
73+
pastThirtyDays.map(date => `stats-requests-${createDayKey(date)}`)
74+
).then(total => {
75+
console.log(
76+
'Requests this month: %s',
77+
total.toLocaleString()
78+
)
79+
})
80+
81+
sumKeys(
82+
pastThirtyDays.map(date => `stats-bandwidth-${createDayKey(date)}`)
83+
).then(total => {
84+
console.log(
85+
'Bandwidth this month: %s',
86+
prettyBytes(total)
87+
)
88+
})

0 commit comments

Comments
 (0)