Skip to content

Commit

Permalink
fix: Update to use Brevo
Browse files Browse the repository at this point in the history
  • Loading branch information
storm1729 committed Dec 22, 2024
1 parent 0008e65 commit d6c82ad
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 156 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
"@formatjs/intl-localematcher": "^0.5.2",
"@geist-ui/react": "^2.2.5",
"@geist-ui/react-icons": "^1.0.1",
"@getbrevo/brevo": "^2.2.0",
"@hcaptcha/react-hcaptcha": "^1.9.2",
"@reacherhq/api": "^0.3.10",
"@sendinblue/client": "^3.3.1",
"@sentry/nextjs": "^8",
"@stripe/stripe-js": "^1.52.0",
"@supabase/auth-ui-react": "^0.4.6",
Expand Down
70 changes: 0 additions & 70 deletions src/app/api/sendinblue/create-contact/route.ts

This file was deleted.

8 changes: 4 additions & 4 deletions src/app/api/v0/check_email/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
checkUserInDB,
isEarlyResponse,
} from "@/app/api/v0/check_email/checkUserInDb";
import { updateSendinblue } from "@/util/sendinblue";
import { updateBrevoLastApiCall } from "@/util/brevo";
import { sentryException } from "@/util/sentry";
import { NextRequest } from "next/server";
import * as Sentry from "@sentry/nextjs";
Expand All @@ -27,15 +27,15 @@ export async function POST(req: NextRequest): Promise<Response> {
const emailInput = (await req.json()) as CheckEmailInput;
const res = await tryAllBackends(emailInput, user);

// Update the LAST_API_CALL field in Sendinblue.
// Update the LAST_API_CALL field in Brevo.
const t2 = performance.now();
try {
await updateSendinblue(user.id, user.sendinblue_contact_id);
await updateBrevoLastApiCall(user.id, user.sendinblue_contact_id);
} catch (err) {
sentryException(err as Error);
}
console.log(
`[🐢] Update Sendinblue: +${Math.round(performance.now() - t2)}ms`
`[🐢] Update Brevo: +${Math.round(performance.now() - t2)}ms`
);

console.log(
Expand Down
10 changes: 9 additions & 1 deletion src/app/auth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createClient } from "@/supabase/server";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createBrevoContact } from "@/util/brevo";

export async function GET(request: Request) {
// The `/auth/callback` route is required for the server-side auth flow implemented
Expand All @@ -13,8 +14,15 @@ export async function GET(request: Request) {
const cookieStore = cookies();
const supabase = createClient(cookieStore);
await supabase.auth.exchangeCodeForSession(code);

// On successful sign-up, create a new contact in Brevo.
const { data, error } = await supabase.auth.getUser();
if (!error && data && data.user) {
// Ignore all errors if we can't get the user
await createBrevoContact(data.user);
}
}

// URL to redirect to after sign in process completes
return NextResponse.redirect(requestUrl.origin);
return NextResponse.redirect(new URL("/dashboard", request.url));
}
86 changes: 86 additions & 0 deletions src/util/brevo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { ContactsApi, ContactsApiApiKeys } from "@getbrevo/brevo";
import { format } from "date-fns";

import { sentryException } from "./sentry";
import { User } from "@supabase/supabase-js";
import { supabaseAdmin } from "@/supabase/supabaseAdmin";

export const brevoApi = new ContactsApi();

brevoApi.setApiKey(
ContactsApiApiKeys.apiKey,
process.env.SENDINBLUE_API_KEY as string
);

/**
* Format a Date into the format accepted by Brevo, which is yyyy-MM-dd.
*/
function brevoDateFormat(d: Date): string {
return format(d, "yyyy-MM-dd");
}

/**
* Creates a new contact in Brevo for the given user.
*/
export async function createBrevoContact(user: User) {
try {
const { body } = await brevoApi.createContact({
email: user.email,
attributes: {
WEBAPP_ENV:
process.env.VERCEL_ENV === "production"
? "production"
: "staging",
SUPABASE_UUID: user.id,
},
listIds: [7], // List #7 is the Reacher sign up contact list.
});

if (!body.id) {
sentryException(
new Error(
`Got invalid body for Brevo create contact: ${JSON.stringify(
body
)}`
)
);
return;
}

await supabaseAdmin
.from("users")
.update({
sendinblue_contact_id: body.id.toString(),
})
.eq("id", user.id);
} catch (apiError) {
console.error("Error creating Brevo contact:", apiError);
// Handle the error as needed
}
}

/**
* Update the LAST_API_CALL field on Brevo.
*/
export async function updateBrevoLastApiCall(
userId: string,
brevoContactId: string | null
): Promise<void> {
if (!brevoContactId) {
throw new Error(
`User ${userId} does not have a sendinblue_contact_id.`
);
}

return brevoApi
.updateContact(brevoContactId, {
attributes: {
SUPABASE_UUID: userId, // This should be set already, but we re-set it just in case.
LAST_API_CALL: brevoDateFormat(new Date()),
},
})
.then(() => {
/* do nothing */
})
.catch(sentryException);
}
44 changes: 0 additions & 44 deletions src/util/sendinblue.ts

This file was deleted.

Loading

0 comments on commit d6c82ad

Please sign in to comment.