-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
75 lines (67 loc) · 1.95 KB
/
bot.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
/* global fetch */
import Prisma from '@prisma/client'
import { sendEmail } from './email.js'
process.env.TZ = 'Europe/Stockholm' // tell node to parse dates without timestamp (e.g. startTime) with Stockholm timezone
const prisma = new Prisma.PrismaClient()
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const alreadyExists = ({ id }) => prisma.appointment.findUnique({ where: { id } })
.then(Boolean)
const notifyUsers = async (appointment) => {
const users = await prisma.user.findMany({
where: {
active: true,
clinics: { has: appointment.clinic }
}
})
for (const user of users) {
await sendEmail({
to: user.email,
subject: `Ny tandläkartid i ${appointment.clinic}!`,
text: [
appointment.description,
`${appointment.startTime.toLocaleString('sv-SE')} i ${appointment.clinic}`,
'https://www.folktandvardenstockholm.se/webbokning/boka-sista-minuten/'
].join('\n')
})
}
}
const bot = async () => {
console.time('fetchAppointments')
const result = await fetch('https://www.folktandvardenstockholm.se/api/booking/lastminutenotcached')
console.timeEnd('fetchAppointments')
const appointments = await result.json()
for (const appointment of appointments) {
if (await alreadyExists(appointment)) {
console.log(`already seen ${appointment.id} skipping`)
continue
}
const {
id,
timeType: {
description
},
clinicName: clinic,
startTime
} = appointment
const savedAppointment = await prisma.appointment.create({
data: {
id,
description,
clinic,
startTime: new Date(startTime)
}
})
console.log('saved appointment', JSON.stringify(savedAppointment))
await notifyUsers(savedAppointment)
}
}
const server = async () => {
try {
await bot()
} catch (error) {
console.error('bot error', error)
}
await sleep(60 * 1000)
server()
}
server()