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
21 changes: 15 additions & 6 deletions lib/utils/useDatabase.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
import { sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { err, ok, type Result } from "neverthrow";
import { cache } from "react";
import type { Database } from "@/drizzle/types";
import * as schema from "../../drizzle/schema";
import { getOwner } from "./useOwner";

const dbInstances = new Map<string, Database>();

export function getDatabaseName(ownerId: string): Result<string, string> {
if (!ownerId.startsWith("org_") && !ownerId.startsWith("user_")) {
return err("Invalid owner ID");
}
return ok(ownerId.toLowerCase().replace(/ /g, "_"));
}

export const database = cache(async (): Promise<Database> => {
export async function database(): Promise<Database> {
const { ownerId } = await getOwner();
if (!ownerId) {
throw new Error("Owner ID not found");
}

return getDatabaseForOwner(ownerId);
});
}

export async function getDatabaseForOwner(ownerId: string): Promise<Database> {
const databaseName = getDatabaseName(ownerId).match(
Expand All @@ -31,10 +32,18 @@ export async function getDatabaseForOwner(ownerId: string): Promise<Database> {
);

const sslMode = process.env.DATABASE_SSL === "true" ? "?sslmode=require" : "";
const connectionString = `${process.env.DATABASE_URL}/${databaseName}${sslMode}`;

return drizzle(`${process.env.DATABASE_URL}/${databaseName}${sslMode}`, {
schema,
});
if (!dbInstances.has(ownerId)) {
dbInstances.set(
ownerId,
drizzle(connectionString, {
schema,
}),
);
}

return dbInstances.get(ownerId)!;
}

export async function deleteDatabase(ownerId: string) {
Expand Down
5 changes: 2 additions & 3 deletions trpc/init.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { auth } from "@clerk/nextjs/server";
import { initTRPC, TRPCError } from "@trpc/server";
import { cache } from "react";
import superjson from "superjson";
import { ZodError } from "zod";
import { SearchService } from "@/lib/search";
import { database } from "@/lib/utils/useDatabase";
import { getOwner, getTimezone } from "@/lib/utils/useOwner";

export const createTRPCContext = cache(async () => {
export const createTRPCContext = async () => {
const timezone = await getTimezone();
const { orgSlug, ownerId } = await getOwner();
const db = await database();
Expand All @@ -18,7 +17,7 @@ export const createTRPCContext = cache(async () => {
ownerId,
orgSlug,
};
});
};

export type Context = Awaited<ReturnType<typeof createTRPCContext>>;
// Avoid exporting the entire t-object
Expand Down