@@ -3,7 +3,10 @@ const level = require('level')
33const then = require ( 'then-levelup' )
44const { 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
811module . 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