Skip to content

Commit e732cae

Browse files
committed
Email worker: Some de-duplication, fix bug with base url handling
1 parent f0ce16d commit e732cae

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

email-worker/src/worker.js

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@ import PostalMime from 'postal-mime';
22
import { EmailMessage } from "cloudflare:email";
33
import { createMimeMessage } from "mimetext";
44

5+
// Helper function to get API endpoint configuration
6+
function getApiConfig(recipient, env) {
7+
const isLocalRequest = recipient.includes('+local');
8+
const baseUrl = (isLocalRequest ? env.local_base_url : env.base_url)?.replace(/\/$/, '');
9+
const selectedEndpoint = `${baseUrl}/process-email`;
10+
const apiKey = isLocalRequest ? env.local_api_key : env.x_api_key;
11+
console.log("Using endpoint:", selectedEndpoint);
12+
return { selectedEndpoint, apiKey };
13+
}
14+
515
// Helper function to calculate size of base64 string
616
function base64Size(base64String) {
717
// Calculate size of decoded base64 - each 4 base64 chars represent 3 bytes
@@ -97,11 +107,8 @@ export default {
97107
}
98108
}
99109

100-
// Determine which API endpoint and key to use based on recipient
101-
const isLocalRequest = recipient.includes('+local');
102-
const baseUrl = isLocalRequest ? env.local_base_url?.replace(/\/$/, '') : env.base_url;
103-
const selectedEndpoint = `${baseUrl}/process-email`;
104-
const apiKey = isLocalRequest ? env.local_api_key : env.x_api_key;
110+
// Get API configuration
111+
const { selectedEndpoint, apiKey } = getApiConfig(recipient, env);
105112

106113
const response = await fetch(selectedEndpoint, {
107114
method: "POST",
@@ -171,10 +178,7 @@ export default {
171178
formData.append('rawHeaders', JSON.stringify(fallbackHeaders));
172179

173180
// Still try to send to the API (use same endpoint and key selection logic)
174-
const isLocalRequest = recipient.includes('+local');
175-
const baseUrl = isLocalRequest ? env.local_base_url?.replace(/\/$/, '') : env.base_url;
176-
const selectedEndpoint = `${baseUrl}/process-email`;
177-
const apiKey = isLocalRequest ? env.local_api_key : env.x_api_key;
181+
const { selectedEndpoint, apiKey } = getApiConfig(recipient, env);
178182

179183
await fetch(selectedEndpoint, {
180184
method: "POST",

0 commit comments

Comments
 (0)