Skip to content

Instantly share code, notes, and snippets.

@AstakhovArtem
Created March 2, 2014 22:58
Show Gist options
  • Save AstakhovArtem/9315242 to your computer and use it in GitHub Desktop.
Save AstakhovArtem/9315242 to your computer and use it in GitHub Desktop.
post.js
function PostsDAO(db) {
"use strict";
if (false === (this instanceof PostsDAO)) {
console.log('Warning: PostsDAO constructor called without "new" operator');
return new PostsDAO(db);
}
var posts = db.collection("posts");
this.insertEntry = function (title, body, tags, author, callback) {
"use strict";
console.log("inserting blog entry" + title + body);
var permalink = title.replace( /\s/g, '_' );
permalink = permalink.replace( /\W/g, '' );
var post = {"title": title,
"author": author,
"body": body,
"permalink":permalink,
"tags": tags,
"comments": [],
"date": new Date()}
posts.insert(post, function (err, result) {
"use strict";
if (err) return callback(err, null);
console.log("Inserted new post");
callback(err, permalink);
});
}
this.getPosts = function(num, callback) {
"use strict";
posts.find().sort('date', -1).limit(num).toArray(function(err, items) {
"use strict";
if (err) return callback(err, null);
console.log("Found " + items.length + " posts");
callback(err, items);
});
}
this.getPostsByTag = function(tag, num, callback) {
"use strict";
posts.find({ tags : tag }).sort('date', -1).limit(num).toArray(function(err, items) {
"use strict";
if (err) return callback(err, null);
console.log("Found " + items.length + " posts");
callback(err, items);
});
}
this.getPostByPermalink = function(permalink, callback) {
"use strict";
posts.findOne({'permalink': permalink}, function(err, post) {
"use strict";
if (err) return callback(err, null);
if (typeof post.comments === 'undefined') {
post.comments = [];
}
for (var i = 0; i < post.comments.length; i++) {
console.log(post.comments[i].num_likes);
if (typeof post.comments[i].num_likes === 'undefined') {
post.comments[i].num_likes = 0;
}
post.comments[i].comment_ordinal = i;
}
callback(err, post);
});
}
this.addComment = function(permalink, name, email, body, callback) {
"use strict";
var comment = {'author': name, 'body': body}
if (email != "") {
comment['email'] = email
}
posts.update({'permalink': permalink}, {'$push': {'comments': comment}}, function(err, numModified) {
"use strict";
if (err) return callback(err, null);
callback(err, numModified);
});
}
this.incrementLikes = function(permalink, comment_ordinal, callback) {
"use strict";
var comments = {};
posts.update({'permalink':permalink}, {'$inc': comments[comment_ordinal].num_likes = 1}, function(err, post){
callback(err, post);
});
posts.findOne({'permalink':permalink}, function(err, post) {
console.log(post);
});
}
}
module.exports.PostsDAO = PostsDAO;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment