forked from wangziqi/gongxue-base
feat: scaffold supabase multi-tenant backend
This commit is contained in:
18
packages/db/src/index.js
Normal file
18
packages/db/src/index.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import pg from 'pg';
|
||||
import { DEFAULT_DATABASE_URL } from '../../config/src/index.js';
|
||||
const { Pool } = pg;
|
||||
export function createPool(options = {}) {
|
||||
return new Pool({
|
||||
connectionString: options.connectionString || process.env.DATABASE_URL || DEFAULT_DATABASE_URL,
|
||||
max: options.max || 10,
|
||||
idleTimeoutMillis: options.idleTimeoutMillis || 30_000,
|
||||
});
|
||||
}
|
||||
export async function query(pool, sql, params = []) {
|
||||
const result = await pool.query(sql, params);
|
||||
return result.rows;
|
||||
}
|
||||
export async function queryOne(pool, sql, params = []) {
|
||||
const rows = await query(pool, sql, params);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
28
packages/db/src/index.ts
Normal file
28
packages/db/src/index.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import pg from 'pg';
|
||||
import { DEFAULT_DATABASE_URL } from '../../config/src/index.js';
|
||||
|
||||
const { Pool } = pg;
|
||||
|
||||
export interface DbPoolOptions {
|
||||
connectionString?: string;
|
||||
max?: number;
|
||||
idleTimeoutMillis?: number;
|
||||
}
|
||||
|
||||
export function createPool(options: DbPoolOptions = {}) {
|
||||
return new Pool({
|
||||
connectionString: options.connectionString || process.env.DATABASE_URL || DEFAULT_DATABASE_URL,
|
||||
max: options.max || 10,
|
||||
idleTimeoutMillis: options.idleTimeoutMillis || 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function query<T = unknown>(pool: pg.Pool, sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
const result = await pool.query(sql, params);
|
||||
return result.rows as T[];
|
||||
}
|
||||
|
||||
export async function queryOne<T = unknown>(pool: pg.Pool, sql: string, params: unknown[] = []): Promise<T | null> {
|
||||
const rows = await query<T>(pool, sql, params);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
Reference in New Issue
Block a user