@@ -49,30 +49,62 @@ app.post('/subscribe', async (c) => {
49
49
}
50
50
51
51
try {
52
- const parsedNewSubscriber = emailSchema . parse ( newSubscriber ) ;
52
+ const parsedEmail = emailSchema . parse ( newSubscriber ) ;
53
53
const client = new NewsletterClient ( BREVO_API_URL , BREVO_API_KEY ) ;
54
+ let sendTemplate = true ;
54
55
55
- await client . createContact ( {
56
- email : parsedNewSubscriber ,
57
- emailBlacklisted : false ,
58
- listIds,
59
- smsBlacklisted : false ,
60
- } ) ;
61
-
62
- const template = await client . getTemplate ( templateId ) ;
63
-
64
- await client . sendEmail ( {
65
- sender : {
66
- id : template . sender . id ,
67
- } ,
68
- subject : template . subject ,
69
- htmlContent : template . htmlContent ,
70
- to : [
71
- {
72
- email : parsedNewSubscriber ,
56
+ try {
57
+ const existingContact = await client . getContact ( parsedEmail ) ;
58
+ const mergedListIds = Array . from (
59
+ new Set ( [ ...existingContact . listIds , ...listIds ] ) ,
60
+ ) ;
61
+ const alreadySubscribed = listIds . some ( ( listId ) =>
62
+ existingContact . listIds . includes ( listId ) ,
63
+ ) ;
64
+
65
+ if ( ! alreadySubscribed ) {
66
+ await client . updateContact ( {
67
+ email : parsedEmail ,
68
+ emailBlacklisted : false ,
69
+ smsBlacklisted : false ,
70
+ listIds : mergedListIds ,
71
+ } ) ;
72
+ }
73
+
74
+ // Contact is already on the list, we should not send a welcoming template
75
+ sendTemplate = ! alreadySubscribed ;
76
+ } catch ( err ) {
77
+ if (
78
+ typeof err === 'object' &&
79
+ err &&
80
+ 'code' in err &&
81
+ err . code === 'document_not_found'
82
+ ) {
83
+ await client . createContact ( {
84
+ email : parsedEmail ,
85
+ emailBlacklisted : false ,
86
+ smsBlacklisted : false ,
87
+ listIds,
88
+ } ) ;
89
+ }
90
+ }
91
+
92
+ if ( sendTemplate ) {
93
+ const template = await client . getTemplate ( templateId ) ;
94
+
95
+ await client . sendEmail ( {
96
+ sender : {
97
+ id : template . sender . id ,
73
98
} ,
74
- ] ,
75
- } ) ;
99
+ subject : template . subject ,
100
+ htmlContent : template . htmlContent ,
101
+ to : [
102
+ {
103
+ email : parsedEmail ,
104
+ } ,
105
+ ] ,
106
+ } ) ;
107
+ }
76
108
77
109
return c . json ( { success : true } , 200 ) ;
78
110
} catch ( e ) {
0 commit comments