Mikael's blog

A developers sixth time trying to maintain a blog

Source Code - Root / controllers / blogPostController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*****************************************
 *   Blog Post Controller
 *****************************************
 *   Author:  mikael.lofjard@gmail.com
 *   Website: http://lofjard.se
 *   License: MIT License
****************************************/
  
var BlogPostController = (function() {
  
  var querystring = require('querystring');
  
  var marked = require('../forked/marked');
  
  var viewManager = require('../viewManager').ViewManager;
  var cacheManager = require('../cacheManager').CacheManager;
  var responseManager = require('../responseManager').ResponseManager;
  var env = require('../environmentManager').EnvironmentManager;
  var misc = require('../misc').Misc;
  
  var db = null;
  
  return {
  
    init: function(dbInit) {
      db = dbInit;
    },
  
    getPost: function(request, response) {
      env.info("Blog Post Controller: GetPost url recieved: " + request.url);
  
      var docId = request.params.id;
  
      db.view('posts/byReadableKeyWithComments', { startkey: [docId], endkey: [docId, 2] }, function (err, doc) {
        if (err || doc.length == 0) {
          if (err) env.info("CouchDB: DB Read error");
          if (doc.length == 0) env.info("CouchDB: No document returned");
          staticFileController.error(request, response, 404);
          return;
        }
  
        var blogpost = doc[0].value;
        blogpost['readableDateTime'] = misc.prettyDate(blogpost.dateTime);
  
        blogpost['renderComments'] = true;
        blogpost['comments'] = new Array();
        for (var i = 1; i < doc.length; i++) {
          blogpost.comments[i-1] = doc[i].value;
          blogpost.comments[i-1]['readableDateTime'] = misc.prettyDate(doc[i].value.dateTime);
        }
  
        // apply syntax highlighting
        blogpost.htmlContent = marked(blogpost.htmlContent);
          
        // add page title
        blogpost.header = {}; 
        blogpost.header.pageTitle = blogpost.title;
  
        // render view
        var responseData = viewManager.renderView(response, 'blogpost', blogpost);
  
        // write to response stream
        responseManager.writeResponse(request, response, responseData);
  
        return;
      });
    },
  
    comment: function(request, response) {
      request.setEncoding('utf8');
      postData = '';
  
      request.addListener('data', function (postDataChunk) {
        //console.log('Handler: Post data recieved.');
        postData += postDataChunk;
      });
  
      request.addListener('end', function () {
        var data = querystring.parse(postData);
  
        if (data.name === null || data.name === '') {
          data.name = 'Anonymous';
        }
        if (data.website === '') {
          data.website = null;
        }
        if (data.website != null)
          {
            data.website = data.website.toLowerCase();
            data.website = data.website.replace(/[^a-z0-9\:\/\.\-\_]/g, '');
            if (data.website.indexOf('http://') != 0 && data.website.indexOf('https://') != 0)
                {
              data.website = 'http://' + data.website;
            }
          }
  
          //write to db
          data.type = "comment";
          data.dateTime = misc.getDateTimeNow();
          db.save(data, function (err, res) {
            if (err) {
              env.info("CouchDB: Error saving comment!");
            }
            cacheManager.clearOnNewComment('/post/' + data.postKey)
          });
  
          //return json
          data.readableDateTime = misc.prettyDate(data.dateTime);
  
          var headers = { "Content-Type" : "application/json;charset=utf-8" };
          var responseData = { headers: headers, content: JSON.stringify(data) };
  
          // write to response stream
          responseManager.writeResponse(request, response, responseData, true);
  
          return;
      });   
    }
  };
  
}());
  
typeof(exports) != 'undefined' ? exports.BlogPostController = BlogPostController : null;