Skip to content

Commit 8be2940

Browse files
committed
Initial commit
0 parents  commit 8be2940

5 files changed

Lines changed: 1223 additions & 0 deletions

File tree

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
blog-views
2+
node_modules
3+
.DS_STORE

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# `mxstbr.blog` view counter
2+
3+
A simple Node microservice to count the views of blogposts on `mxstbr.blog`.
4+
5+
## Uses
6+
7+
- [`micro`](https://github.com/zeit/micro) to create the service.
8+
- [`level`](https://github.com/level/level) to store the data.
9+
- [`then-levelup`](https://github.com/then/then-levelup) to promisify `level`.
10+
11+
## Gotchas
12+
13+
Currently this uses `level` for data storage, which doesn't have atomic operations. That means a view that happens while another view is registered will override the first view.
14+
15+
## License
16+
17+
Copyright ©️ 2016 Maximilian Stoiber, licensed under the MIT License.

index.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const url = require('url')
2+
const level = require('level')
3+
const then = require('then-levelup')
4+
const { send, createError } = require('micro')
5+
6+
const db = then(level('blog-views'))
7+
8+
module.exports = async function (req, res) {
9+
// Check that a blogpost is provided
10+
const { pathname } = url.parse(req.url)
11+
if (pathname.length <= 1) {
12+
throw createError(400, 'Please include a path to a blogpost.')
13+
}
14+
// Get the views
15+
let views
16+
try {
17+
views = parseInt(await db.get(pathname), 10)
18+
} catch (err) {
19+
// If the post doesn't have views yet, initialise the post with one view
20+
await db.put(pathname, 1)
21+
send(res, 200, { views: 1 })
22+
return
23+
}
24+
// Increment the views and send them back to client
25+
await db.put(pathname, views + 1)
26+
send(res, 200, { views: views + 1 })
27+
}

package.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "blog-view-counter",
3+
"version": "1.0.0",
4+
"description": "A simple node microservice to count the views of a blogpost.",
5+
"main": "index.js",
6+
"scripts": {
7+
"start": "micro -p 3000 -H localhost index.js",
8+
"dev": "NODE_ENV=development nodemon --config package.json index.js"
9+
},
10+
"author": "Max Stoiber <contact@mxstbr.com> (http://mxstbr.com/)",
11+
"license": "MIT",
12+
"dependencies": {
13+
"level": "^1.5.0",
14+
"levelplus": "^0.0.5",
15+
"micro": "^6.1.0",
16+
"then-levelup": "^1.0.2"
17+
},
18+
"devDependencies": {},
19+
"execMap": {
20+
"js": "micro -p 3000 -H localhost"
21+
}
22+
}

0 commit comments

Comments
 (0)