Skip to content

Commit

Permalink
fix: workaround drizzle auto-connecting to db
Browse files Browse the repository at this point in the history
  • Loading branch information
Fractal-Tess committed May 31, 2024
1 parent 43f189f commit 0308b95
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 10 deletions.
2 changes: 1 addition & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
node_modules
.git
.gitignore
.env
.env*
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ WORKDIR /app

COPY . .

ENV BUILDING true

RUN npm install
RUN npm run build

Expand Down
26 changes: 17 additions & 9 deletions src/db/index.ts
Original file line number Diff line number Diff line change
@@ -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 };
7 changes: 7 additions & 0 deletions src/env.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
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(),
DB_USER: z.string(),
DB_PASS: z.string(),
DB_DATABASE: z.string(),
},
skipValidation: BUILDING,
});

0 comments on commit 0308b95

Please sign in to comment.