-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbapis.ts
65 lines (51 loc) · 1.81 KB
/
dbapis.ts
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
import { Appwrite } from "appwrite";
import { apiEndpoint, projectID, chatMessagesCollectionID } from "./config"
const sdk = new Appwrite()
sdk
.setEndpoint(apiEndpoint)
.setProject(projectID)
sdk.account.get().catch(() => {
sdk.account.createAnonymousSession().catch(console.error)
})
export async function countMessagesInRoom(roomName) {
const response = await sdk.database.listDocuments(
chatMessagesCollectionID, [`roomName=${roomName}`]
)
return response.sum
}
export async function deleteRoom(roomName) {
const filteredChatDataCollection =
await sdk.database.listDocuments(
chatMessagesCollectionID,
[`roomName=${roomName}`]
)
// remove messages in room
for (const doc of filteredChatDataCollection.documents) {
sdk.database.deleteDocument(chatMessagesCollectionID, doc["$id"])
}
}
export async function getMessagesByRoomName(roomName) {
const response = await sdk.database.listDocuments(
chatMessagesCollectionID,
[`roomName=${roomName}`],
100, // limit messages -- 100 is max allowed by server
0, // offset value
"timestamp", // order field
"DESC", // descending order
)
return response.documents.reverse() // last 100 messages, in correct order
}
export async function sendMessage(roomName, message, sender) {
return sdk.database.createDocument(chatMessagesCollectionID, {
roomName: roomName,
messageData: message,
sender: sender,
timestamp: Date.now()
}, ["*"], ["*"]) // world-writable may not be optimal but it's convenient :P
}
export function onMessageListUpdated(roomName, callback) {
sdk.subscribe(`documents`, response => {
if (response.payload.roomName == roomName)
callback(response.payload)
})
}