initial commit
[browser-rts.git] / src / repository / mail.ts
1 import { Repository } from "./base";
2 import { v4 as uuid } from 'uuid';
3
4 export type Message = {
5     id: string;
6     from_account: string;
7     to_account: string;
8     type: string;
9     sent_at: number;
10     read_at: number;
11     subject: string;
12     message: string;
13 }
14
15 export type MessageWithNames = {
16     username: string;
17 } & Message;
18
19 export class MailRepository extends Repository<Message> {
20     constructor() {
21         super('mail');
22     }
23
24     async createSystemMessage(from: string, to: string, subject: string, message: string) {
25         const msg: Message = {
26             id: uuid(),
27             from_account: from,
28             to_account: to,
29             type: 'system',
30             sent_at: Date.now(),
31             read_at: 0,
32             subject: subject,
33             message: message
34         };
35
36         await this.Insert(msg);
37         return msg;
38     }
39
40     async markAsRead(id: string, to: string) {
41         return this.Save({read_at: Date.now()}, {
42             id: id,
43             to_account: to
44         });
45     }
46
47     async getMessage(id: string, to: string): Promise<MessageWithNames> {
48         const res = await this.db.raw<MessageWithNames[]>(`select m.*, a.username 
49         from mail m
50         join accounts a on a.id = m.from_account
51         where m.to_account = ? 
52         and m.id = ?
53         limit 1
54         `, [to, id]);
55
56         return res.pop();
57     }
58
59     async listReceivedMessages(to: string): Promise<MessageWithNames[]> {
60         return this.db.raw<MessageWithNames[]>(`select m.*, a.username 
61         from mail m 
62         join accounts a on a.id = m.from_account 
63         where m.to_account = ? 
64         order by sent_at desc`, to);
65     }
66 }