This repository was archived by the owner on Oct 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmessage.js
96 lines (85 loc) · 2.42 KB
/
message.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
//@flow
import striptags from 'striptags';
const { db } = require('./db');
import { addQueue } from '../utils/workerQueue';
const { listenToNewDocumentsIn } = require('./utils');
const { setThreadLastActive } = require('./thread');
import markdownLinkify from '../utils/markdown-linkify';
import type { PaginationOptions } from '../utils/paginate-arrays';
export type MessageTypes = 'text' | 'media';
const getMessage = (messageId: string): Promise<Object> => {
return db
.table('messages')
.get(messageId)
.run();
};
const getMessages = (threadId: String): Promise<Array<Object>> => {
return db
.table('messages')
.between([threadId, db.minval], [threadId, db.maxval], {
index: 'threadIdAndTimestamp',
})
.orderBy({ index: 'threadIdAndTimestamp' })
.run();
};
const getLastMessage = (threadId: string): Promise<Object> => {
return db
.table('messages')
.getAll(threadId, { index: 'threadId' })
.max('timestamp')
.run();
};
const getMediaMessagesForThread = (
threadId: String
): Promise<Array<Object>> => {
return getMessages(threadId).then(messages =>
messages.filter(({ messageType }) => messageType === 'media')
);
};
const storeMessage = (message: Object, userId: string): Promise<Object> => {
// Insert a message
return db
.table('messages')
.insert(
Object.assign({}, message, {
timestamp: new Date(),
senderId: userId,
content: {
body:
message.messageType === 'media'
? message.content.body
: // For text messages linkify URLs and strip HTML tags
markdownLinkify(striptags(message.content.body)),
},
}),
{ returnChanges: true }
)
.run()
.then(result => result.changes[0].new_val)
.then(message => {
addQueue('message notification', { message, userId });
if (message.threadType === 'story') {
setThreadLastActive(message.threadId, message.timestamp);
}
return message;
});
};
const listenToNewMessages = (cb: Function): Function => {
return listenToNewDocumentsIn('messages', cb);
};
const getMessageCount = (threadId: string): Promise<number> => {
return db
.table('messages')
.getAll(threadId, { index: 'threadId' })
.count()
.run();
};
module.exports = {
getMessage,
getMessages,
getLastMessage,
getMediaMessagesForThread,
storeMessage,
listenToNewMessages,
getMessageCount,
};