Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions apps/api/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,25 @@ import type { Env } from "./types";

type Database = ReturnType<typeof drizzle<typeof schema>>;

let cachedUrl: string | undefined;
let cachedDb: Database | undefined;

export function getDb(env: Env) {
if (!env.SUPABASE_POOLER_DATABASE_URL) {
throw new Error("SUPABASE_POOLER_DATABASE_URL is not configured.");
}

const client = postgres(env.SUPABASE_POOLER_DATABASE_URL, {
connect_timeout: 10,
fetch_types: false,
idle_timeout: 1,
max: 1,
prepare: false,
ssl: "require",
});
if (!cachedDb || cachedUrl !== env.SUPABASE_POOLER_DATABASE_URL) {
const client = postgres(env.SUPABASE_POOLER_DATABASE_URL, {
connect_timeout: 10,
idle_timeout: 20,
max: 1,
prepare: false,
});

cachedDb = drizzle(client, { schema });
cachedUrl = env.SUPABASE_POOLER_DATABASE_URL;
}

return drizzle(client, { schema }) satisfies Database;
return cachedDb;
}
14 changes: 4 additions & 10 deletions apps/api/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ type ClerkClaims = Record<string, unknown> & {

type AuthOptions = {
allowQueryToken?: boolean;
resolveUser?: boolean;
};

let cachedClerkClient: ClerkClient | undefined;
Expand Down Expand Up @@ -168,14 +167,11 @@ async function upsertAuthUser(env: Env, payload: ClerkClaims): Promise<AuthUser>
return user;
}

function authMiddleware({
allowQueryToken = false,
resolveUser = true,
}: AuthOptions = {}): MiddlewareHandler<AppBindings> {
function authMiddleware(options: AuthOptions = {}): MiddlewareHandler<AppBindings> {
return async (c, next) => {
const token = getToken(
c.req.header("authorization"),
allowQueryToken ? c.req.query("token") : undefined,
options.allowQueryToken ? c.req.query("token") : undefined,
);

if (!hasAuthMaterial(c.req.raw, token)) {
Expand All @@ -188,16 +184,14 @@ function authMiddleware({
unauthorized();
}

if (resolveUser) {
c.set("authUser", await upsertAuthUser(c.env, payload));
}
c.set("authUser", await upsertAuthUser(c.env, payload));

await next();
};
}

export const requireAuth = authMiddleware();
export const requireRealtimeAuth = authMiddleware({ allowQueryToken: true, resolveUser: false });
export const requireRealtimeAuth = authMiddleware({ allowQueryToken: true });

export const optionalAuth: MiddlewareHandler<AppBindings> = async (c, next) => {
const token = getToken(c.req.header("authorization"), undefined);
Expand Down
Loading