-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathcanvasDiscussions.js
96 lines (87 loc) · 2.47 KB
/
canvasDiscussions.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
const canvasAPI = require('node-canvas-api')
const flatten = arr => arr.reduce((acc, cur) =>
Array.isArray(cur)
? [...acc, ...cur]
: [...acc, cur]
, [])
const flattenTopicAndReplies = discussions => {
return discussions.reduce((acc, discussion) => {
const timestamp = discussion.timestamp
const authorId = discussion.authorId
const discussionId = discussion.id
const topicTitle = discussion.topicTitle
const topicMessage = discussion.topicMessage
const replies = discussion.replies
acc.push({
type: 'topic',
timestamp,
authorId,
discussionId,
topicTitle,
topicMessage
})
flatten(replies).forEach(reply => {
acc.push({
type: 'reply',
timestamp: reply.timestamp,
parentId: reply.parentId,
authorId: reply.authorId,
message: reply.message
})
})
return acc
}, [])
}
const getDiscussionTopicIds = async courseId => {
const discussionTopics = await canvasAPI.getDiscussionTopics(courseId)
return discussionTopics.map(discussionTopic => discussionTopic.id)
}
const getNestedReplies = (replyObj, topicId) => {
const replies = replyObj.hasOwnProperty('replies')
? flatten(
// recursion in real life!
replyObj.replies.map(replyObj => getNestedReplies(replyObj, topicId))
) : []
return [{
authorId: replyObj.user_id,
message: replyObj.message,
likes: replyObj.rating_sum,
timestamp: replyObj.created_at,
parentId: replyObj.parent_id || topicId,
id: replyObj.id
}, ...replies]
}
const getDiscussions = async courseId => {
const discussionTopicIds = await getDiscussionTopicIds(courseId)
const discussionAndTopic = await Promise.all(
discussionTopicIds
.map(topicId => Promise.all([
canvasAPI.getFullDiscussion(courseId, topicId),
canvasAPI.getDiscussionTopic(courseId, topicId)
]))
)
return discussionAndTopic.map(([discussion, topic]) => {
const topicTitle = topic.title
const topicMessage = topic.message
const author = topic.author
const timestamp = topic.created_at
const topicId = topic.id
const replies = discussion.view.length > 0
? discussion.view
.filter(x => !x.deleted)
.map(reply => getNestedReplies(reply, topicId))
: []
return {
topicTitle,
topicMessage,
id: topicId,
authorId: author.id || '',
timestamp,
replies
}
})
}
module.exports = {
getDiscussions,
flattenTopicAndReplies
}