11const url = require ( 'url' )
22const level = require ( 'level' )
33const then = require ( 'then-levelup' )
4- const { send, createError } = require ( 'micro' )
4+ const { send, createError, sendError } = require ( 'micro' )
55
66const db = then ( level ( 'blog-views' ) )
77
@@ -11,17 +11,21 @@ module.exports = async function (req, res) {
1111 if ( pathname . length <= 1 ) {
1212 throw createError ( 400 , 'Please include a path to a blogpost.' )
1313 }
14- // Get the views
15- let views
14+ if ( req . method !== 'GET' ) {
15+ throw createError ( 400 , 'Please make a GET request.' )
16+ }
1617 try {
17- views = parseInt ( await db . get ( pathname ) , 10 )
18+ const views = parseInt ( await db . get ( pathname ) , 10 )
19+ // Increment the views and send them back to client
20+ await db . put ( pathname , views + 1 )
21+ send ( res , 200 , { views : views + 1 } )
1822 } 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+ if ( err . notFound ) {
24+ // Initialise the post with one view
25+ await db . put ( pathname , 1 )
26+ send ( res , 200 , { views : 1 } )
27+ } else {
28+ throw createError ( 500 , 'Something went wrong, sorry about that.' )
29+ }
2330 }
24- // Increment the views and send them back to client
25- await db . put ( pathname , views + 1 )
26- send ( res , 200 , { views : views + 1 } )
2731}
0 commit comments