-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPost.js
200 lines (180 loc) · 4.72 KB
/
Post.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
const postsCollection = require("../db")
.db()
.collection("posts");
const ObjectID = require("mongodb").ObjectID;
const User = require("./User");
const sanitizeHTML = require("sanitize-html");
let Post = function(data, userid, requestedPostId) {
this.data = data;
this.errors = [];
this.userid = userid;
this.requestedPostId = requestedPostId;
};
Post.prototype.cleanUp = function() {
if (typeof this.data.title != "string") {
this.data.title = "";
}
if (typeof this.data.body != "string") {
this.data.body = "";
}
// get rid of any bogus properties
this.data = {
title: sanitizeHTML(this.data.title.trim(), {
allowedTags: [],
allowedAttributes: {}
}),
body: sanitizeHTML(this.data.body.trim(), {
allowedTags: [],
allowedAttributes: {}
}),
createdDate: new Date(),
author: ObjectID(this.userid)
};
};
Post.prototype.validate = function() {
if (this.data.title == "") {
this.errors.push("You must provide a title.");
}
if (this.data.body == "") {
this.errors.push("You must provide post content.");
}
};
Post.prototype.create = function() {
return new Promise((resolve, reject) => {
this.cleanUp();
this.validate();
if (!this.errors.length) {
// save post into database
postsCollection
.insertOne(this.data)
.then(info => {
resolve(info.ops[0]._id);
})
.catch(() => {
this.errors.push("Please try again later.");
reject(this.errors);
});
} else {
reject(this.errors);
}
});
};
Post.prototype.update = function() {
return new Promise(async (resolve, reject) => {
try {
let post = await Post.findSingleById(this.requestedPostId, this.userid);
if (post.isVisitorOwner) {
// actually update the db
let status = await this.actuallyUpdate();
resolve(status);
} else {
reject();
}
} catch {
reject();
}
});
};
Post.prototype.actuallyUpdate = function() {
return new Promise(async (resolve, reject) => {
this.cleanUp();
this.validate();
if (!this.errors.length) {
await postsCollection.findOneAndUpdate(
{ _id: new ObjectID(this.requestedPostId) },
{ $set: { title: this.data.title, body: this.data.body } }
);
resolve("success");
} else {
resolve("failure");
}
});
};
Post.reusablePostQuery = function(uniqueOperations, visitorId) {
return new Promise(async function(resolve, reject) {
let aggOperations = uniqueOperations.concat([
{
$lookup: {
from: "users",
localField: "author",
foreignField: "_id",
as: "authorDocument"
}
},
{
$project: {
title: 1,
body: 1,
createdDate: 1,
authorId: "$author",
author: { $arrayElemAt: ["$authorDocument", 0] }
}
}
]);
let posts = await postsCollection.aggregate(aggOperations).toArray();
// clean up author property in each post object
posts = posts.map(function(post) {
post.isVisitorOwner = post.authorId.equals(visitorId);
post.authorId = post.isVisitorOwner ? visitorId : undefined;
post.author = {
username: post.author.username,
avatar: new User(post.author, true).avatar
};
return post;
});
resolve(posts);
});
};
Post.findSingleById = function(id, visitorId) {
return new Promise(async function(resolve, reject) {
if (typeof id != "string" || !ObjectID.isValid(id)) {
reject();
return;
}
let posts = await Post.reusablePostQuery(
[{ $match: { _id: new ObjectID(id) } }],
visitorId
);
if (posts.length) {
console.log(posts[0]);
resolve(posts[0]);
} else {
reject();
}
});
};
Post.findByAuthorId = function(authorId) {
return Post.reusablePostQuery([
{ $match: { author: authorId } },
{ $sort: { createdDate: -1 } }
]);
};
Post.delete = function(postIdToDelete, currentUserId) {
return new Promise(async (resolve, reject) => {
try {
let post = await Post.findSingleById(postIdToDelete, currentUserId);
if (post.isVisitorOwner) {
await postsCollection.deleteOne({ _id: new ObjectID(postIdToDelete) });
resolve();
} else {
reject();
}
} catch {
reject();
}
});
};
Post.search = function(searchTerm) {
return new Promise(async (resolve, reject) => {
if (typeof searchTerm == "string") {
let posts = await Post.reusablePostQuery([
{ $match: { $text: { $search: searchTerm } } },
{ $sort: { score: { $meta: "textScore" } } }
]);
resolve(posts);
} else {
reject();
}
});
};
module.exports = Post;