Skip to content

Commit 66f7fb0

Browse files
committed
Save time of visits to make nice graphs easier
1 parent c3c4eec commit 66f7fb0

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

index.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ const level = require('level')
33
const then = require('then-levelup')
44
const { send, createError, sendError } = require('micro')
55

6-
const db = then(level('blog-views'))
6+
const db = then(level('blog-views', {
7+
keyEncoding: 'json',
8+
valueEncoding: 'json'
9+
}))
710

811
module.exports = async function (req, res) {
912
// Check that a page is provided
@@ -16,21 +19,22 @@ module.exports = async function (req, res) {
1619
}
1720
const shouldIncrement = query.inc !== 'false' && query.inc !== false
1821
try {
19-
const views = parseInt(await db.get(pathname), 10)
20-
// Increment the views and send them back to client
22+
const { views } = await db.get(pathname)
23+
// Add a view and send the total views back to the client
2124
if (shouldIncrement) {
22-
await db.put(pathname, views + 1)
25+
views.push({ time: Date.now() })
26+
await db.put(pathname, { views })
2327
}
2428
if (req.method === 'GET') {
25-
send(res, 200, { views: shouldIncrement ? views + 1 : views })
29+
send(res, 200, { views: views.length })
2630
} else {
2731
send(res, 200)
2832
}
2933
} catch (err) {
3034
if (err.notFound) {
3135
// Initialise the page with one view
3236
if (shouldIncrement) {
33-
await db.put(pathname, 1)
37+
await db.put(pathname, { views: [{ time: Date.now() }] })
3438
}
3539
if (req.method === 'GET') {
3640
send(res, 200, { views: shouldIncrement ? 1 : 0 })

0 commit comments

Comments
 (0)