· 6 years ago · Oct 12, 2019, 01:52 PM
1export class UserConversationView {
2 constructor(conversationController, userController) {
3 this.conversationController = conversationController;
4 this.userController = userController;
5 }
6
7 async mapConversationsWithMsgs(conversation) {
8 const msg = await this.conversationController.getLatestMsg(conversation.id);
9 // console.log(msg);
10 return { ...conversation, latest_message: msg };
11 }
12
13 async getRecentConversationSummaries() {
14 const rc = await this.conversationController.getCurrentUserConversation();
15 const fc = rc.filter(rc => rc.id && rc.with_user_id);
16
17 const cMsgs = await Promise.all(
18 fc.map(c => this.mapConversationsWithMsgs(c))
19 );
20
21 return cMsgs;
22 }
23}
24
25import { BaseController } from "./BaseController";
26
27export class ConversationController extends BaseController {
28 constructor(conversationModel) {
29 super();
30
31 if (!conversationModel) {
32 throw "can't initialize controller without a Model";
33 }
34 this.conversationModel = conversationModel;
35 }
36 async getCurrentUserConversation() {
37 // Ideally this sends an API Key which determines which is the current user.
38 return await this.conversationModel.fetchConversations();
39 }
40
41 async getLatestMsg(conversationId) {
42 const msgs = await this.getConversatioById(conversationId);
43
44 if (msgs.length === 0) return {};
45
46 // Return the first message of the sorted array i-e latest message
47 return this.sortByDate(msgs)[0];
48 }
49 async getConversatioById(conversationId) {
50 return await this.conversationModel.fetchMessages(conversationId);
51 }
52 // can do a generic sort function that receives a key and sort by that key.
53 sortByDate(conversations) {
54 return conversations.sort((a,b) => {
55 if (a.created_at < b.created_at) {
56 return 1;
57 }
58 if (a.created_at > b.created_at) {
59 return -1;
60 }
61 return 0;
62 });
63 }
64}