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
23 changes: 18 additions & 5 deletions apps/api/src/db/client.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
import { env } from 'node:process';
import type { Logger } from 'drizzle-orm';
import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import { Context } from 'hono';
import postgres from 'postgres';
import { AppContext } from '@/index';

const DATABASE_URL = env.INFISCAL_DATABASE_URL;
// Logs each SQL statement in non-prod (params omitted — they can hold PII).
class QueryLogger implements Logger {
logQuery(query: string): void {
console.log(`[db] ${query}`);
}
}

export const useDb = (ctx: Context<AppContext>) => {
export const useDb = (ctx: Context<AppContext>): PostgresJsDatabase => {
const storedDb: PostgresJsDatabase | undefined = ctx.get('db');

if (storedDb) {
return storedDb;
}

const sql = postgres(DATABASE_URL);
const newDb = drizzle(sql);
const connectionString = ctx.env.HYPERDRIVE?.connectionString ?? ctx.env.INFISCAL_DATABASE_URL;

const sql = postgres(connectionString, {
max: 5,
fetch_types: false,
});

const newDb = drizzle(sql, {
logger: ctx.env.NODE_ENV !== 'production' ? new QueryLogger() : undefined,
});

ctx.set('db', newDb);

Expand Down
1 change: 1 addition & 0 deletions apps/api/worker-configuration.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ declare namespace Cloudflare {
ASSETS_BUCKET: R2Bucket;
WHITEBOARD_ASSETS_BUCKET: R2Bucket;
API_RATE_LIMITER: RateLimit;
HYPERDRIVE?: Hyperdrive;
}
}
interface Env extends Cloudflare.Env {}
Expand Down
3 changes: 3 additions & 0 deletions apps/api/wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@
"bucket_name": "coderscreen-whiteboard",
},
],
"hyperdrive": [
{ "binding": "HYPERDRIVE", "id": "c205221f01db4e28bcc6ba8c2a1798a2" },
],
"env": {
"staging": {
"name": "coderscreen-api-staging",
Expand Down
Loading