Attempt to improve unsent mail

This commit is contained in:
Thomas Ruoff
2022-06-23 17:39:30 +02:00
committed by Thomas Ruoff
parent a462cd1c14
commit 942066bc7a
4 changed files with 119 additions and 97 deletions

View File

@@ -2,12 +2,11 @@ import { Booking } from '../db/booking'
import { getBaseURL } from '../helpers/url'
import { daysFormatFrontend } from './date'
import { generateCalendarEntry } from './ical'
import { retryWithDelay } from './retryWithDelay'
import sgMail from '@sendgrid/mail'
const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY
const ADMIN_EMAIL = process.env.ADMIN_EMAIL
const FROM_EMAIL = process.env.FROM_EMAIL
const SENDGRID_URL = 'https://api.sendgrid.com/v3/mail/send'
if (!SENDGRID_API_KEY) {
throw new Error('NO SENDGRID_API_KEY set!')
@@ -21,6 +20,8 @@ if (!FROM_EMAIL) {
throw new Error('No FROM_EMAIL set!')
}
sgMail.setApiKey(SENDGRID_API_KEY)
const footer = `
Viele Grüße
@@ -29,6 +30,7 @@ Thomas Ruoff
Pfadi Bussle Wart
Tel. 0151/212 253 62
${getBaseURL()}
`
function getReceivedBookingBookerText(booking: Booking): string {
@@ -210,36 +212,22 @@ async function sendMail({
}[]
}): Promise<void> {
const data = {
personalizations: [
{
to,
},
],
to,
from,
subject,
content: [{ type: 'text/plain', value: textPlainContent }],
text: textPlainContent,
attachments,
}
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${SENDGRID_API_KEY}`,
},
body: JSON.stringify(data),
try {
await sgMail.send(data)
} catch (error) {
console.error(error)
if (error.response) {
console.error(error.response.body)
}
// TODO: stuff into DB if failed and retry later
}
return retryWithDelay({
run: async () => {
const resp = await fetch(SENDGRID_URL, fetchOptions)
const bodyText = await resp.text()
if (!resp.ok) {
throw new Error(
`Failed to send mail with status ${resp.status}: ${bodyText}`
)
}
},
})
}

View File

@@ -1,20 +0,0 @@
import pRetry from 'p-retry'
export function retryWithDelay<T>({
run,
delay = 1000,
}: {
run: () => Promise<T>
delay?: number
}) {
return pRetry(run, {
retries: 2,
onFailedAttempt: (error) => {
console.info(
`Attempt ${error.attemptNumber}: ${error.message}. ${error.retriesLeft} retries left`
)
return new Promise((resolve) => setTimeout(resolve, delay))
},
})
}