From 0308b959d4318cf2dcacee89a06c2a352d2870b3 Mon Sep 17 00:00:00 2001 From: Fractal-Tess Date: Fri, 31 May 2024 07:27:29 +0300 Subject: [PATCH] fix: workaround drizzle auto-connecting to db --- .dockerignore | 2 +- Dockerfile | 2 ++ src/db/index.ts | 26 +++++++++++++++++--------- src/env.js | 7 +++++++ 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/.dockerignore b/.dockerignore index f52e085..17fa299 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,4 +2,4 @@ node_modules .git .gitignore -.env \ No newline at end of file +.env* \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 1590529..02ac7de 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,6 +9,8 @@ WORKDIR /app COPY . . +ENV BUILDING true + RUN npm install RUN npm run build diff --git a/src/db/index.ts b/src/db/index.ts index 46f480b..3d82e22 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -1,15 +1,23 @@ -import { drizzle } from 'drizzle-orm/mysql2'; +import { MySql2Client, drizzle } from 'drizzle-orm/mysql2'; import mysql from 'mysql2/promise'; -import { ENV } from '@/env'; +import { BUILDING, ENV } from '@/env'; import * as schema from './schema'; -const connection = await mysql.createConnection({ - host: ENV.DB_HOST, - user: ENV.DB_USER, - database: ENV.DB_DATABASE, - password: ENV.DB_PASS, -}); +async function createDbConnection() { + if (BUILDING) { + const mockConnection = {} as unknown as MySql2Client; + return drizzle(mockConnection, { schema, mode: 'default' }); + } -export const db = drizzle(connection, { schema, mode: 'default' }); + const connection = await mysql.createConnection({ + host: ENV.DB_HOST, + user: ENV.DB_USER, + database: ENV.DB_DATABASE, + password: ENV.DB_PASS, + }); + return drizzle(connection, { schema, mode: 'default' }); +} + +export const db = await createDbConnection(); export { schema }; diff --git a/src/env.js b/src/env.js index 159078b..ba95344 100644 --- a/src/env.js +++ b/src/env.js @@ -1,6 +1,12 @@ import { createEnv } from '@t3-oss/env-nextjs'; import { z } from 'zod'; +export const BUILDING = + z + .enum(['true'], { message: 'BUILDING must be "TRUE" if set' }) + .optional() + .parse(process.env.BUILDING) ?? false; + export const ENV = createEnv({ server: { DB_HOST: z.string(), @@ -8,4 +14,5 @@ export const ENV = createEnv({ DB_PASS: z.string(), DB_DATABASE: z.string(), }, + skipValidation: BUILDING, });