import * as SendgridClient from '@sendgrid/client' import * as UserController from '../../controllers/user' import { prismaClient as prisma } from '../../prismaClient' SendgridClient.setApiKey(process.env.SENDGRID_API_KEY) /** * This script is used to update users email error information based on what SendGrid * provide us. */ async function updateUserCantDeliverEmailReason(userEmail, reason) { if (!reason) { console.log('No reason specified') return } const user = await UserController.querySingleUser({ email: userEmail, }) if (user) { console.log('updating user email reason') return prisma.user.update({ where: { id: user.id }, data: { cantDeliverEmailFullReason: reason }, }) } } function updateUserEmailInformationBasedOnSendGridData() { return Promise.all([ SendgridClient.request({ method: 'GET', url: '/v3/suppression/bounces', }), SendgridClient.request({ method: 'GET', url: '/v3/suppression/invalid_emails', }), SendgridClient.request({ method: 'GET', url: '/v3/suppression/blocks', }), SendgridClient.request({ method: 'GET', url: '/v3/suppression/unsubscribes', }), SendgridClient.request({ method: 'GET', url: '/v3/suppression/spam_reports', }), ]) .then(async ([bounces, invalidEmails, blocks, unsubscribes, spamReports]) => { const [, bouncesData] = bounces await bouncesData.reduce(async (promise, emailData) => { await promise await updateUserCantDeliverEmailReason(emailData.email, emailData.reason) }, Promise.resolve) const [, invalidEmailsData] = invalidEmails await invalidEmailsData.reduce(async (promise, emailData) => { await promise await updateUserCantDeliverEmailReason(emailData.email, emailData.reason) }, Promise.resolve) const [, blocksData] = blocks await blocksData.reduce(async (promise, emailData) => { await promise await updateUserCantDeliverEmailReason(emailData.email, emailData.reason) }, Promise.resolve) const [, unsubscribesData] = unsubscribes await unsubscribesData.reduce(async (promise, emailData) => { await promise await updateUserCantDeliverEmailReason( emailData.email, 'User unsubscribed from the mailing list' ) }, Promise.resolve) const [, spamReportsData] = spamReports await spamReportsData.reduce(async (promise, emailData) => { await promise await updateUserCantDeliverEmailReason(emailData.email, 'User marked the emails as SPAM') }, Promise.resolve) }) .catch((err) => { console.log('err', err) }) } updateUserEmailInformationBasedOnSendGridData() // prisma.users({ where: { cantDeliverEmailFullReason_not: null } }).then(users => { // console.log('users.length', users.length) // users.reduce(async (promise, user) => { // await promise // await prisma.updateUser({ where: { id: user.id }, data: { cantDeliverEmail: true } }) // }, Promise.resolve) // })