Skip to content

Commit

Permalink
perf: Faster queries
Browse files Browse the repository at this point in the history
  • Loading branch information
amaury1093 committed Dec 12, 2023
1 parent 3124c34 commit 664f91d
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 30 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"dev": "next dev",
"build": "next build",
"gen:license": "ts-node -P scripts/tsconfig.json scripts/license.ts",
"lint": "tsc --noEmit && prettier -w */**/*.{ts,tsx}",
"lint": "tsc --noEmit && prettier -w */**/*.{ts,tsx} && next lint",
"start": "next start"
},
"dependencies": {
Expand Down
11 changes: 7 additions & 4 deletions src/pages/api/v0/check_email.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const POST = async (
return;
}

const { userId, sentResponse } = await checkUserInDB(req, res);
const { user, sentResponse } = await checkUserInDB(req, res);
if (sentResponse) {
return;
}
Expand Down Expand Up @@ -77,7 +77,7 @@ const POST = async (
.from<SupabaseCall>("calls")
.insert({
endpoint: "/v0/check_email",
user_id: userId,
user_id: user.id,
backend: output.debug?.server_name,
domain: output.syntax.domain,
verification_id: verificationId,
Expand All @@ -100,7 +100,10 @@ const POST = async (

// Cleanup
await Promise.all([
updateSendinblue(userId).then(() => {
updateSendinblue(
user.id,
user.sendinblue_contact_id
).then(() => {
const d8 = performance.now() - startTime;
console.log(
`[🐢] updateSendinblue: ${Math.round(d8)}ms`
Expand All @@ -115,7 +118,7 @@ const POST = async (
`[🐢] ch1.close: ${Math.round(d7)}ms`
);
}),
]);
]).catch(sentryException);

const d9 = performance.now() - startTime;
console.log(`[🐢] Final response: ${Math.round(d9)}ms`);
Expand Down
22 changes: 16 additions & 6 deletions src/util/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { RateLimiterRes } from "rate-limiter-flexible";

import { subApiMaxCalls } from "./subs";
import { SupabaseSubscription } from "./supabaseClient";
import { SupabaseSubscription, SupabaseUser } from "./supabaseClient";
import { supabaseAdmin } from "./supabaseServer";

// Helper method to wait for a middleware to execute before continuing
Expand Down Expand Up @@ -41,12 +41,12 @@ export const cors = initMiddleware(

type CheckUserReturnType =
| {
userId?: undefined;
user?: undefined;
subAndCalls?: undefined;
sentResponse: true;
}
| {
userId: string;
user: SupabaseUser;
subAndCalls: SubAndCalls;
sentResponse: false;
};
Expand All @@ -71,7 +71,7 @@ export async function checkUserInDB(
}

const { data, error } = await supabaseAdmin
.from<SubAndCalls>("sub_and_calls")
.from<SupabaseUser>("users")
.select("*")
.eq("api_token", token);
if (error) {
Expand All @@ -81,8 +81,18 @@ export async function checkUserInDB(
res.status(401).json({ error: "Invalid API token." });
return { sentResponse: true };
}
const user = data[0];

const res2 = await supabaseAdmin
.from<SubAndCalls>("sub_and_calls")
.select("*")
.eq("user_id", user.id)
.single();
if (res2.error) {
throw res2.error;
}

const subAndCalls = data[0];
const subAndCalls = res2.data;

// Set rate limit headers.
const now = new Date();
Expand Down Expand Up @@ -118,7 +128,7 @@ export async function checkUserInDB(
return { sentResponse: true };
}

return { userId: subAndCalls.user_id, subAndCalls, sentResponse: false };
return { user, subAndCalls, sentResponse: false };
}

interface SubAndCalls {
Expand Down
24 changes: 5 additions & 19 deletions src/util/sendinblue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { ContactsApi, ContactsApiApiKeys } from "@sendinblue/client";
import { format } from "date-fns";

import { sentryException } from "./sentry";
import { SupabaseUser } from "./supabaseClient";
import { supabaseAdmin } from "./supabaseServer";

export const sendinblueApi = new ContactsApi();

Expand All @@ -26,26 +24,14 @@ export async function updateSendinblue(
userId: string,
sendinblueContactId?: string
): Promise<void> {
let sibId = sendinblueContactId;
if (!sibId) {
const res = await supabaseAdmin
.from<SupabaseUser>("users")
.select("sendinblue_contact_id")
.eq("id", userId);
if (res.error) {
throw res.error;
}
if (!res.data?.length || !res.data[0].sendinblue_contact_id) {
throw new Error(
`User ${userId} does not have a sendinblue_contact_id.`
);
}

sibId = res.data[0].sendinblue_contact_id;
if (!sendinblueContactId) {
throw new Error(
`User ${userId} does not have a sendinblue_contact_id.`
);
}

return sendinblueApi
.updateContact(sibId, {
.updateContact(sendinblueContactId, {
attributes: {
SUPABASE_UUID: userId, // This should be set already, but we re-set it just in case.
LAST_API_CALL: sendinblueDateFormat(new Date()),
Expand Down

1 comment on commit 664f91d

@vercel
Copy link

@vercel vercel bot commented on 664f91d Dec 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.