eletrotupi / tcc/ commit / 9cd93e6

api: build the Resend client on first send

The module constructed the client from RESEND_API_KEY at import, so
every module that reached it needed the key just to load. App boot and
the DB-free unit suite both crashed through the queue's mail import
chain, instead of failing only when an email was actually sent. The
client is now created lazily inside sendEmail
Pedro Lucas Porcellis porcellis@eletrotupi.com · 9 days ago 9cd93e6ab48e317d51b0bdf9066dc5852cda738f Browse files
Parents ab21e9f
Changed files
1
Additions
+11
Deletions
-3
api/src/lib/mail.ts modified+11 -3
api/src/lib/mail.ts
1 1
import { Resend } from 'resend';
2 2

3 -
// Initialized once when the module is first imported
4 -
export const resend = new Resend(process.env.RESEND_API_KEY);
3 +
// Built on first send, not at import: a module that reads a secret at import
4 +
// time makes every importer require it, so a missing RESEND_API_KEY crashes
5 +
// app boot and any test that transitively imports this file.
6 +
let client: Resend | undefined;
7 +

8 +
const getResend = (): Resend => {
9 +
  if (!client) client = new Resend(process.env.RESEND_API_KEY);
10 +

11 +
  return client;
12 +
};
5 13

6 14
// XXX: Bleh, resend doesn't expose their types so w/e
7 15
export async function sendEmail(opts: any): Promise<any> {
8 -
  return await resend.emails.send({
16 +
  return await getResend().emails.send({
9 17
    from: process.env.RESEND_FROM ?? 'naoresponda@updates.cabotia.dev',
10 18
    ...opts,
11 19
  });
12 20
}