后端建立 TypeScript 构建链路
This commit is contained in:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user