Skip to content

Commit c3c4eec

Browse files
committed
Add ability to not increment the views
1 parent f433ae4 commit c3c4eec

2 files changed

Lines changed: 13 additions & 6 deletions

File tree

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ And that's it! 🎉
2323

2424
### Tracking views
2525

26-
To track a view simply send a request to `/<yourpagepath>`. If you send a `GET` request, the request will return the total views. If you send a `POST` request, the views will increment but you're not going to get the total views back.
26+
To track a view simply send a request to `/<yourpagepath>`. If you send a `GET` request, the request will increment the views and return the total views. If you send a `POST` request, the views will increment but you're not going to get the total views back.
27+
28+
If you don't want to increment the views during a `GET` request, set `inc` to `false` in your query parameter. (`/<yourpagepath>?inc=false`)
2729

2830
This is how you'd track pageviews for a website: (though note that this can be used to track anything you want)
2931

index.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,33 @@ const db = then(level('blog-views'))
77

88
module.exports = async function (req, res) {
99
// Check that a page is provided
10-
const { pathname } = url.parse(req.url)
10+
const { pathname, query } = url.parse(req.url, /* parseQueryString */ true)
1111
if (pathname.length <= 1) {
1212
throw createError(400, 'Please include a path to a page.')
1313
}
1414
if (req.method !== 'GET' && req.method !== 'POST') {
1515
throw createError(400, 'Please make a GET or a POST request.')
1616
}
17+
const shouldIncrement = query.inc !== 'false' && query.inc !== false
1718
try {
1819
const views = parseInt(await db.get(pathname), 10)
1920
// Increment the views and send them back to client
20-
await db.put(pathname, views + 1)
21+
if (shouldIncrement) {
22+
await db.put(pathname, views + 1)
23+
}
2124
if (req.method === 'GET') {
22-
send(res, 200, { views: views + 1 })
25+
send(res, 200, { views: shouldIncrement ? views + 1 : views })
2326
} else {
2427
send(res, 200)
2528
}
2629
} catch (err) {
2730
if (err.notFound) {
2831
// Initialise the page with one view
29-
await db.put(pathname, 1)
32+
if (shouldIncrement) {
33+
await db.put(pathname, 1)
34+
}
3035
if (req.method === 'GET') {
31-
send(res, 200, { views: 1 })
36+
send(res, 200, { views: shouldIncrement ? 1 : 0 })
3237
} else {
3338
send(res, 200)
3439
}

0 commit comments

Comments
 (0)