-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.ts
73 lines (61 loc) · 1.42 KB
/
index.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
import * as dotenv from 'dotenv'
dotenv.config()
import * as cron from 'node-cron'
import * as moment from 'moment'
import { sendEmail } from './src/utils/helper'
import { log } from './src/utils/logger'
import {
getAllScheduledMessages,
getScheduledMessagesBeforeTime,
clearAllScheduledMessages,
} from './src/queue'
import { hasUnsubscribed, unsubscribeUser } from './src/unsubscribe'
import { init } from './src/automation'
import { runWorkflow } from './src/workflow'
const task = cron.schedule(
'* * * * *',
async () => {
await sendMessagesNow()
},
{
scheduled: false,
}
)
const start = async () => {
task.start()
}
const stop = () => {
task.stop()
}
const destroy = () => {
task.destroy()
}
const sendMessagesNow = async () => {
const today = moment.utc().toDate()
const messagesToBeSent = await getScheduledMessagesBeforeTime(today)
if (messagesToBeSent) {
for (const message of messagesToBeSent) {
const {
email: { sendTo },
} = message
const isUnsubscribed = await hasUnsubscribed(sendTo)
if (isUnsubscribed) {
log(`The user ${sendTo} you are trying to send a message to has already unsubscribed`)
} else {
sendEmail(message)
}
}
}
}
export {
init,
start,
stop,
destroy,
runWorkflow,
getAllScheduledMessages,
getScheduledMessagesBeforeTime,
clearAllScheduledMessages,
sendMessagesNow,
unsubscribeUser,
}