11// import needed libraries (installed with npm)
22var express = require ( 'express' ) ;
3- var fs = require ( 'fs' ) ;
43var exphbs = require ( 'express3-handlebars' ) ;
4+ var db = require ( './jankydb' ) ;
55
66var app = express ( ) ;
7-
8- var POSTS_FILE = 'posts.json' ;
7+ var db = new db . JankyDB ( 'posts.json' ) ;
98
109// detail, not sure why express does't do this automatically
1110app . use ( express . urlencoded ( ) ) ;
@@ -15,11 +14,12 @@ app.use(express.logger());
1514app . engine ( 'handlebars' , exphbs ( ) ) ;
1615app . set ( 'view engine' , 'handlebars' ) ;
1716
17+ // serve static files (jankyblog.js)
18+ app . use ( express . static ( __dirname + '/public' ) ) ;
19+
1820// tell express how to handle requests
1921app . get ( '/' , function ( req , res ) {
20- fs . readFile ( POSTS_FILE , function ( err , contents ) {
21- if ( err ) throw err ;
22- var posts = JSON . parse ( contents ) ;
22+ db . getPosts ( function ( posts ) {
2323 res . render ( 'index' , { posts : posts } ) ;
2424 } ) ;
2525} ) ;
@@ -29,28 +29,32 @@ app.get('/write', function(req, res) {
2929} ) ;
3030
3131app . post ( '/save' , function ( req , res ) {
32- // load posts
33- fs . readFile ( POSTS_FILE , function ( err , contents ) {
34- if ( err ) throw err ;
35- var posts = JSON . parse ( contents ) ;
36- // construct our new post from data received in request
37- var post = {
38- title : req . body . title ,
39- body : req . body . body
40- } ;
41- // insert our new post
42- posts . push ( post ) ;
43- // serialize posts back to a string
44- var serialized = JSON . stringify ( posts , null , 2 ) ;
45- // save posts with new one added
46- fs . writeFile ( POSTS_FILE , serialized , function ( err ) {
47- if ( err ) throw err ;
48- console . log ( 'posts saved' ) ;
49- res . redirect ( '/' ) ; // send user back to index
50- } ) ;
32+ var post = {
33+ title : req . body . title ,
34+ body : req . body . body ,
35+ likes : 0
36+ } ;
37+ db . addPost ( post , function ( ) {
38+ console . log ( 'posts saved' ) ;
39+ res . redirect ( '/' ) ; // send user back to front page
40+ } ) ;
41+ } ) ;
42+
43+ app . get ( '/like/:post_id' , function ( req , res ) {
44+ var post_id = req . params . post_id ;
45+ db . changePostLikes ( post_id , 1 , function ( ) {
46+ res . send ( 201 ) ;
47+ } ) ;
48+ } ) ;
49+
50+ app . get ( '/unlike/:post_id' , function ( req , res ) {
51+ var post_id = req . params . post_id ;
52+ db . changePostLikes ( post_id , - 1 , function ( ) {
53+ res . send ( 201 ) ;
5154 } ) ;
5255} ) ;
5356
57+ // start it up
5458app . listen ( 3000 , function ( ) {
5559 console . log ( 'listening on http://localhost:3000/' ) ;
5660} ) ;
0 commit comments