This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Article.js
346 lines (307 loc) · 11 KB
/
Article.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
const { ds, namespace } = require('./Datastore.js');
const slugify = require('slugify');
module.exports = {
async create(aArticleData, aAuthorUsername) {
// Get author data
const authorUser = (await ds.get(ds.key({ namespace, path: ['User', aAuthorUsername] })))[0];
if (!authorUser) {
throw new Error(`User does not exist: [${aAuthorUsername}]`);
}
const articleSlug = slugify('' + aArticleData.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36);
const timestamp = (new Date()).getTime();
const newArticle = {
slug: articleSlug,
title: aArticleData.title,
description: aArticleData.description,
body: aArticleData.body,
tagList: aArticleData.tagList ? aArticleData.tagList : [],
createdAt: timestamp,
updatedAt: timestamp,
author: aAuthorUsername,
favoritedBy: [],
};
await ds.upsert({
key: ds.key({ namespace, path: ['Article', newArticle.slug] }),
data: newArticle,
});
newArticle.author = {
username: aAuthorUsername,
bio: authorUser.bio,
image: authorUser.bio,
following: false,
};
newArticle.favorited = false;
newArticle.favoritesCount = 0;
delete newArticle.favoritedBy;
return newArticle;
},
async update(aSlug, aMutation, aUpdaterUsername) {
const article = (await ds.get(ds.key({ namespace, path: ['Article', aSlug] })))[0];
if (!article) {
throw new Error(`Article not found: [${aSlug}]`);
}
if (aUpdaterUsername !== article.author) {
throw new Error('Only author can update article');
}
if (aMutation.title) {
article.title = aMutation.title;
}
if (aMutation.description) {
article.description = aMutation.description;
}
if (aMutation.body) {
article.body = aMutation.body;
}
await ds.update(article);
return await this.get(aSlug, aUpdaterUsername);
},
async get(aSlug, aReaderUsername) {
const article = (await ds.get(ds.key({ namespace, path: ['Article', aSlug] })))[0];
if (!article) {
throw new Error(`Article not found: [${aSlug}]`);
}
delete article[ds.KEY];
// Get author data
const authorUser = (await ds.get(ds.key({ namespace, path: ['User', article.author] })))[0];
/* istanbul ignore next */
if (!authorUser) {
throw new Error(`User does not exist: [${article.author}]`);
}
article.author = {
username: authorUser.username,
bio: authorUser.bio,
image: authorUser.image,
following: false,
};
// If reader's username is provided, populate following & favorited bits
article.favorited = false;
article.favoritesCount = article.favoritedBy.length;
if (aReaderUsername) {
article.author.following = authorUser.followers.includes(aReaderUsername);
article.favoritedBy.includes(aReaderUsername);
}
delete article.favoritedBy;
return article;
},
async delete(aSlug, aUsername) {
const article = (await ds.get(ds.key({ namespace, path: ['Article', aSlug] })))[0];
if (!article) {
throw new Error(`Article not found: [${aSlug}]`);
}
const user = (await ds.get(ds.key({ namespace, path: ['User', aUsername] })))[0];
if (!user) {
throw new Error(`User does not exist: [${aUsername}]`);
}
if (article.author !== user.username) {
throw new Error(`Only author can delete article: [${article.author}]`);
}
await ds.delete(ds.key({ namespace, path: ['Article', aSlug] }));
return null;
},
async getAll(options) {
let query = ds.createQuery(namespace, 'Article')
.order('createdAt', { descending: true });
if (!options) {
options = {};
}
if (options.tag) {
query = query.filter('tagList', '=', options.tag);
} else if (options.author) {
query = query.filter('author', '=', options.author);
} else if (options.favoritedBy) {
query = query.filter('favoritedBy', '=', options.favoritedBy);
}
if (options.limit) {
query = query.limit(options.limit);
} else {
query = query.limit(20);
}
if (options.offset) {
query = query.offset(options.offset);
}
const articles = (await query.run(query))[0];
for (const article of articles) {
delete article[ds.KEY];
// Get author info for this article
const authorUser = (await ds.get(ds.key({ namespace, path: ['User', article.author] })))[0];
article.author = {
username: authorUser.username,
bio: authorUser.bio,
image: authorUser.image,
following: false,
};
article.favorited = false;
article.favoritesCount = article.favoritedBy.length;
if (options.reader) {
article.author.following = authorUser.followers.includes(options.reader);
article.favorited = article.favoritedBy.includes(options.reader);
}
delete article.favoritedBy;
}
return articles;
},
async getFeed(aUsername, options) {
const user = (await ds.get(ds.key({ namespace, path: ['User', aUsername] })))[0];
if (!user) {
throw new Error(`User not found: [${aUsername}]`);
}
if (!options) {
options = {};
}
if (!options.limit) {
options.limit = 20;
}
if (!options.offset) {
options.offset = 0;
}
// For each followed user, get authored articles
let articles = [];
for (let i = 0; i < user.following.length; ++i) {
const followedUser = (await ds.get(ds.key({ namespace, path: ['User', user.following[i]] })))[0];
const query = ds.createQuery(namespace, 'Article').filter('author', '=', user.following[i]);
const articlesByThisAuthor = (await query.run())[0];
for (const article of articlesByThisAuthor) {
delete article[ds.KEY];
article.favorited = article.favoritedBy.includes(aUsername);
article.favoritesCount = article.favoritedBy.length;
delete article.favoritedBy;
article.author = {
username: followedUser.username,
bio: followedUser.bio,
image: followedUser.image,
following: true,
};
articles.push(article);
}
}
// Sort merged articles by createdAt descending
articles = articles.sort((a, b) => b.createdAt - a.createdAt);
return articles.slice(options.offset, options.offset + options.limit);
},
async favoriteArticle(aSlug, aUsername) {
return await this.mutateFavoriteBit(aSlug, aUsername, true);
},
async unfavoriteArticle(aSlug, aUsername) {
return await this.mutateFavoriteBit(aSlug, aUsername, false);
},
async mutateFavoriteBit(aSlug, aUsername, aFavoriteBit) {
// Verify user exists
if (!aUsername) {
throw new Error('User must be specified');
}
const favoriterUser = (await ds.get(ds.key({ namespace, path: ['User', aUsername] })))[0];
if (!favoriterUser) {
throw new Error(`User does not exist: [${aUsername}]`);
}
// Get article to mutate
const article = (await ds.get(ds.key({ namespace, path: ['Article', aSlug] })))[0];
if (!article) {
throw new Error(`Article does not exist: [${aSlug}]`);
}
// First remove this author if already in list, and add back if favoriting
article.favoritedBy = article.favoritedBy.filter(e => e !== aUsername);
if (aFavoriteBit) {
article.favoritedBy.push(aUsername);
}
await ds.update(article);
article.favorited = aFavoriteBit;
article.favoritesCount = article.favoritedBy.length;
delete article.favoritedBy;
article[ds.KEY];
// Get author data
const authorUser = (await ds.get(ds.key({ namespace, path: ['User', article.author] })))[0];
article.author = {
username: authorUser.username,
bio: authorUser.bio,
image: authorUser.image,
following: authorUser.followers.includes(aUsername),
};
return article;
},
async createComment(aSlug, aCommentAuthorUsername, aCommentBody) {
const key = ds.key({ namespace, path: ['Article', aSlug, 'Comment'] });
const timestamp = (new Date()).getTime();
const commentData = {
body: aCommentBody,
createdAt: timestamp,
updatedAt: timestamp,
author: aCommentAuthorUsername,
};
await ds.insert({ key, data: commentData });
commentData.id = key.id;
const commentAuthorUser = (await ds.get(ds.key({ namespace, path: ['User', aCommentAuthorUsername] })))[0];
commentData.author = {
username: aCommentAuthorUsername,
bio: commentAuthorUser.bio,
image: commentAuthorUser.image,
following: false,
};
return commentData;
},
async deleteComment(aSlug, aCommentId, aDeleterUsername) {
const commentKey = ds.key({ namespace, path: ['Article', aSlug, 'Comment', parseInt(aCommentId)] });
const comment = (await ds.get(commentKey))[0];
if (!comment) {
throw new Error(`Comment not found: [${aSlug}/${aCommentId}]`);
}
// Only comment's author can delete comment
if (comment.author !== aDeleterUsername) {
throw new Error('Only comment author can delete comment');
}
await ds.delete(commentKey);
return null;
},
async getAllComments(aSlug, aReaderUsername) {
let comments = (await ds.createQuery(namespace, 'Comment')
.hasAncestor(ds.key({ namespace, path: ['Article', aSlug] })).run())[0];
comments = comments.sort((a, b) => b.createdAt - a.createdAt);
for (const comment of comments) {
comment.id = comment[ds.KEY].id;
delete comment[ds.KEY];
// Get comment author info
const authorUser = (await ds.get(ds.key({ namespace, path: ['User', comment.author] })))[0];
comment.author = {
username: authorUser.username,
bio: authorUser.bio,
image: authorUser.image,
following: false,
};
if (aReaderUsername) {
comment.author.following = authorUser.followers.includes(aReaderUsername);
}
}
return comments;
},
async getAllTags() {
const tags = (await ds.createQuery(namespace, 'Article').select('tagList').run())[0];
const dedupeObj = {};
for (let i = 0; i < tags.length; ++i) {
dedupeObj[tags[i].tagList] = 1;
}
return Object.keys(dedupeObj);
},
testutils: {
async __deleteAllArticles() {
/* istanbul ignore next */
if (!namespace.startsWith('test')) {
console.warn(`__deleteAllArticles: namespace does not start with "test" but is [${namespace}], skipping.`);
return;
}
const articleKeys = (await ds.createQuery(namespace, 'Article').select('__key__').run())[0];
articleKeys.forEach(async (articleKey) => {
await ds.delete(articleKey[ds.KEY]);
});
},
async __deleteAllComments() {
/* istanbul ignore next */
if (!namespace.startsWith('test')) {
console.warn(`__deleteAllComments: namespace does not start with "test" but is [${namespace}], skipping.`);
return;
}
const commentKeys = (await ds.createQuery(namespace, 'Comment').select('__key__').run())[0];
commentKeys.forEach(async (commentKey) => {
await ds.delete(commentKey[ds.KEY]);
});
},
},
};