后端建立 TypeScript 构建链路

This commit is contained in:
yml
2026-05-21 13:36:38 +08:00
parent 25671078d6
commit 1476522ab5
18 changed files with 798 additions and 101 deletions
@@ -1,10 +1,11 @@
import { Pool } from 'pg'
import type { PoolClient, QueryResult, QueryResultRow } from 'pg'
import { runtimeConfig } from '../config/runtime.js'
let poolInstance = null
let poolInstance: Pool | null = null
export function getDb() {
export function getDb(): Pool {
if (!poolInstance) {
poolInstance = new Pool({
connectionString: String(runtimeConfig.database?.url || '').trim(),
@@ -16,12 +17,20 @@ export function getDb() {
return poolInstance
}
export async function query(text, params = []) {
export async function query(text: string, params?: unknown[]): Promise<QueryResult<any>>
export async function query<T extends QueryResultRow>(
text: string,
params?: unknown[],
): Promise<QueryResult<T>>
export async function query<T extends QueryResultRow>(
text: string,
params: unknown[] = [],
): Promise<QueryResult<T>> {
const pool = getDb()
return pool.query(text, params)
return pool.query<T>(text, params)
}
export async function withTransaction(fn) {
export async function withTransaction<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await getDb().connect()
try {
@@ -37,7 +46,7 @@ export async function withTransaction(fn) {
}
}
export async function closeDb() {
export async function closeDb(): Promise<void> {
if (!poolInstance) {
return
}