Skip to content

Instantly share code, notes, and snippets.

@nelsonprsousa
Created July 8, 2024 18:46
Show Gist options
  • Save nelsonprsousa/5f9d25160584cfa14530070a0c033f6f to your computer and use it in GitHub Desktop.
Save nelsonprsousa/5f9d25160584cfa14530070a0c033f6f to your computer and use it in GitHub Desktop.
Singleton with Qwik
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import type * as schema from './schema';
let _db!: PostgresJsDatabase<typeof schema> | null;
export function getDb(): PostgresJsDatabase<typeof schema> {
if (!_db) {
throw new Error('DB is not set in the singleton.');
}
return _db;
}
export function initializeDbIfNeeded(
factory: () => PostgresJsDatabase<typeof schema> | null,
): void {
if (!_db) {
_db = factory();
}
}
import type { RequestHandler } from '@builder.io/qwik-city';
import type { EnvGetter } from '@builder.io/qwik-city/middleware/request-handler';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { initializeDbIfNeeded } from '~/infrastructure/db';
import * as schema from '~/infrastructure/db/schema';
import { LoggerFactory } from '~/utils/logging/LoggerFactory';
export const onRequest: RequestHandler = async ({ env }) => {
initializeDbIfNeeded(initDatabaseClient(env));
};
const initDatabaseClient = (env: EnvGetter) => () => {
try {
const host = env.get('DATABASE_HOST')!;
const port = parseInt(env.get('DATABASE_PORT')!, 10);
const name = env.get('DATABASE_NAME')!;
const username = env.get('DATABASE_USERNAME')!;
const password = env.get('DATABASE_PASSWORD')!;
const isToLogQuery = env.get('IS_TO_LOG_QUERY') === 'true';
const queryClient = postgres({
host: host,
port: port,
database: name,
username: username,
password: password,
});
return drizzle(queryClient, {
schema,
logger: isToLogQuery
? {
logQuery(query: string, params: unknown[]): void {
LoggerFactory.getLogger().debug({
message: 'Debugging drizzle query',
query,
params,
});
},
}
: undefined,
});
} catch (e) {
LoggerFactory.getLogger().fatal({
message: 'Error initializing db.',
err: e,
});
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment