-
Notifications
You must be signed in to change notification settings - Fork 0
/
article-provider.js
92 lines (82 loc) · 2.87 KB
/
article-provider.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
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
ArticleProvider = function(host, port) {
this.db= new Db('article-provider', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
ArticleProvider.prototype.getCollection= function(callback) {
this.db.collection('articles', function(error, article_collection) {
if( error ) callback(error);
else callback(null, article_collection);
});
};
ArticleProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
ArticleProvider.prototype.findById = function(id, callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.findOne({_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
if( error ) callback(error)
else callback(null, result)
});
}
});
};
ArticleProvider.prototype.save = function(articles, callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
if( typeof(articles.length)=="undefined")
articles = [articles];
for( var i =0;i< articles.length;i++ ) {
article = articles[i];
article.created_at = new Date();
if( article.comments === undefined ) article.comments = [];
for(var j =0;j< article.comments.length; j++) {
article.comments[j].created_at = new Date();
}
}
article_collection.insert(articles, function() {
callback(null, articles);
});
}
});
};
ArticleProvider.prototype.remove = function(articles,rtitle,ruser, callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback(error)
else {
article_collection.remove( { title: rtitle,user: ruser }, function() {
callback(null, articles);
});
}
});
};
ArticleProvider.prototype.addCommentToArticle = function(articleId, comment, callback) {
this.getCollection(function(error, article_collection) {
if( error ) callback( error );
else {
article_collection.update(
{_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(articleId)},
{"$push": {comments: comment}},
function(error, article){
if( error ) callback(error);
else callback(null, article)
});
}
});
};
exports.ArticleProvider = ArticleProvider;