Skip to content

Commit

Permalink
smiplify email provider selection logic with early return
Browse files Browse the repository at this point in the history
  • Loading branch information
chribjel committed Feb 23, 2024
1 parent c768342 commit 7a98ef7
Showing 1 changed file with 31 additions and 44 deletions.
75 changes: 31 additions & 44 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,68 +5,55 @@ import { sendEmail as sendEmailPostmark } from "./adapters/postmark";
export function createClient(providers: Provider[]) {
return {
async sendEmail(email: SendEmailInput) {
let result;
for (const provider of providers) {
const providerType = provider.type;
try {
switch (providerType) {
case "custom":
{
const res = await provider.sendEmail(email);
if (res.error) {
throw new Error(res.error);
}
result = {
type: providerType,
index: providers.indexOf(provider),
custom: res,
};
case "custom": {
const res = await provider.sendEmail(email);
if (res.error) {
throw new Error(res.error);
}
break;
return {
type: providerType,
index: providers.indexOf(provider),
custom: res,
};
}

case "resend":
{
const res = await sendEmailResend(provider, email);
if (res.error) {
throw res.error;
}
result = {
type: providerType,
index: providers.indexOf(provider),
resend: res as any,
};
case "resend": {
const res = await sendEmailResend(provider, email);
if (res.error) {
throw res.error;
}
break;
return {
type: providerType,
index: providers.indexOf(provider),
resend: res as any,
};
}

case "postmark":
{
const res = await sendEmailPostmark(provider, email);
if (res.ErrorCode) {
throw new Error(res.Message);
}
result = {
type: providerType,
index: providers.indexOf(provider),
postmark: res,
};
case "postmark": {
const res = await sendEmailPostmark(provider, email);
if (res.ErrorCode) {
throw new Error(res.Message);
}
break;
return {
type: providerType,
index: providers.indexOf(provider),
postmark: res,
};
}

default:
providerType satisfies never;
throw new Error("Invalid provider type");
}
if (result) {
break;
}
} catch (error) {
console.error(error);
}
}
if (!result) {
throw new Error("No email provider available");
}
return result;
throw new Error("No email provider available");
},
};
}

0 comments on commit 7a98ef7

Please sign in to comment.