-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.ts
78 lines (56 loc) · 1.87 KB
/
model.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
64
65
66
67
68
69
70
71
72
73
74
75
76
import { ParsedMail } from 'mailparser';
import { type InsertOneResult, type Collection, type WithId, MongoClient, type FindOptions } from 'mongodb';
import * as core from '@actions/core';
type ParsedMailDocument = WithId<ParsedMail>;
const mongoUrl = core.getInput("mongo-url") || process.env.MONGO_URL;
class EmailsModel {
private col!: Collection;
private client!: Promise<MongoClient>;
private _ready: boolean = false;
constructor() {
if (!mongoUrl) {
throw new Error('mongo url must be non empty string');
}
this.client = new MongoClient(mongoUrl).connect();
this.client.then((client) => {
this.col = client.db("tests").collection("emails_received");
})
}
isready(): Promise<void> {
if (this._ready) {
return Promise.resolve();
}
return new Promise(resolve => this.client.then(() => {
this._ready = true;
resolve();
}
));
}
createNewEmail(email: ParsedMail): Promise<InsertOneResult> {
return this.col.insertOne(email);
}
findBySubject(subject: string, options?: FindOptions<ParsedMail>) {
return this.col.find<ParsedMailDocument>({ subject }, options ?? {});
}
fundByReceipientEmailAddress(address: string, options?: FindOptions<ParsedMail>) {
return this.col.find<ParsedMailDocument>({ 'to.value.address': address }, options ?? {});
}
findByEmailContent(content: string, options?: FindOptions<ParsedMail>) {
return this.col.find<ParsedMailDocument>({ text: content }, options ?? {});
}
}
// always make sure connection is ready in case initial connect has a delay
export const Emails = new Proxy(new EmailsModel(), {
get(target, prop: keyof EmailsModel) {
const thing = target[prop];
if (typeof thing !== 'function') {
return thing;
}
return function(...args: any[]) {
return new Promise(resolve => target.isready().then(() => {
// @ts-ignore-error
resolve(thing.apply(target, args));
}));
}
}
});