diff --git a/src/lib/mongo/mongodb.ts b/src/lib/mongo/mongodb.ts index acd4108a..07f4a282 100644 --- a/src/lib/mongo/mongodb.ts +++ b/src/lib/mongo/mongodb.ts @@ -3,17 +3,14 @@ import { MongoClient } from 'mongodb'; import 'dotenv/config'; const MONGODB_URI = process.env.MONGODB_URI; -if (!MONGODB_URI) { - throw new Error('Invalid/Missing environment variable: "MONGODB_URI"'); -} const uri = MONGODB_URI; const options = {}; let client; -let clientPromise: Promise; +let clientPromise: Promise | undefined; -if (process.env.NODE_ENV === 'development') { +if (process.env.NODE_ENV === 'development' && uri) { /* * In development mode, use a global variable so that the value * Is preserved across module reloads caused by HMR (Hot Module Replacement). @@ -23,7 +20,7 @@ if (process.env.NODE_ENV === 'development') { global._mongoClientPromise = client.connect(); } clientPromise = global._mongoClientPromise; -} else { +} else if (uri) { // In production mode, it's best to not use a global variable. client = new MongoClient(uri, options); clientPromise = client.connect(); diff --git a/src/lib/trpc/routes/users.ts b/src/lib/trpc/routes/users.ts index b20572e7..d398bd46 100644 --- a/src/lib/trpc/routes/users.ts +++ b/src/lib/trpc/routes/users.ts @@ -36,6 +36,10 @@ async function getPrismaAndMongoUser(userId: string) { throw new TRPCError({ message: 'Migration has already been performed', code: 'CONFLICT' }); } + if (!clientPromise) { + throw new TRPCError({ message: "Couldn't connect V2's Mongo database", code: 'INTERNAL_SERVER_ERROR' }); + } + const client = await clientPromise; const mongoUser = await client.db().collection('users').findOne({ email: prismaUser?.email }); if (!mongoUser) { @@ -91,6 +95,9 @@ export const users = t.router({ checkV2MigrationAvailability: t.procedure.query(async ({ ctx }) => { try { const { mongoUser } = await getPrismaAndMongoUser(ctx.userId); + if (!clientPromise) { + throw new TRPCError({ message: "Couldn't connect V2's Mongo database", code: 'INTERNAL_SERVER_ERROR' }); + } const client = await clientPromise; const mesocycleTemplatesCount = await client @@ -121,6 +128,9 @@ export const users = t.router({ .input(z.strictObject({ bodyweight: z.number(), duration: z.number() })) .mutation(async ({ ctx, input }) => { const { mongoUser } = await getPrismaAndMongoUser(ctx.userId); + if (!clientPromise) { + throw new TRPCError({ message: "Couldn't connect V2's Mongo database", code: 'INTERNAL_SERVER_ERROR' }); + } const client = await clientPromise; const mesocycleTemplates = await client