From 7e566798ddb2c146ab0314441212eee289bfab69 Mon Sep 17 00:00:00 2001 From: valentinkolb Date: Sat, 26 Oct 2024 01:28:03 +0200 Subject: [PATCH] feat(emailApi): added live feedback of send status for frontend --- emailApi/main.go | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/emailApi/main.go b/emailApi/main.go index 5e78bde..8c13c9f 100644 --- a/emailApi/main.go +++ b/emailApi/main.go @@ -12,7 +12,7 @@ import ( "net/mail" ) -// sendEmailToUser sends an email notification to the user +// sendEmailToUser sends an email notification to a recipient of the email record func sendEmailToUser(app *pocketbase.PocketBase, registry *template.Registry, recipient *models.Record, sender *models.Record, emailRecord *models.Record) error { // check if recipient and message are set and recipient is not the sender if recipient == nil || emailRecord == nil || sender == nil { @@ -67,6 +67,7 @@ func sendEmailToUser(app *pocketbase.PocketBase, registry *template.Registry, re return nil } +// sendEmails sends an email notification to the recipients of the email record@ func sendEmails(app *pocketbase.PocketBase, emailRecord *models.Record) { registry := template.NewRegistry() @@ -94,14 +95,24 @@ func sendEmails(app *pocketbase.PocketBase, emailRecord *models.Record) { // check if there was an error sending the email if err != nil { logger.LogErrorF("%v", err) - } else { - sendToIds = append(sendToIds, recipient.Id) + continue + } + + // add recipient id to sendToIds + sendToIds = append(sendToIds, recipient.Id) + + // update email sentTo field, this will be overwritten for each recipient + // we update it for every iteration to provide live feedback on the frontend + emailRecord.Set("sentTo", sendToIds) + + // save email record + if err := app.Dao().SaveRecord(emailRecord); err != nil { + logger.LogErrorF("Error saving email record: %v", err) } } - // set email record fields + // mark email as sent emailRecord.Set("sentTo", sendToIds) - emailRecord.Set("wasSent", true) // save email record if err := app.Dao().SaveRecord(emailRecord); err != nil { @@ -121,12 +132,12 @@ func InitEmailApi(app *pocketbase.PocketBase, _ *core.ServeEvent) error { app.OnModelAfterCreate("emails").Add(func(e *core.ModelEvent) error { // get created message record - createdMessageRecord, err := app.Dao().FindRecordById("emails", e.Model.GetId()) + createdEmailRecord, err := app.Dao().FindRecordById("emails", e.Model.GetId()) if err != nil { return err } - go sendEmails(app, createdMessageRecord) + go sendEmails(app, createdEmailRecord) return nil })