112 lines
2.7 KiB
TypeScript
112 lines
2.7 KiB
TypeScript
import { Pool } from 'pg'
|
|
|
|
// 创建数据库连接池
|
|
const pool = new Pool({
|
|
connectionString: process.env.DATABASE_URL,
|
|
max: 20, // 最大连接数
|
|
idleTimeoutMillis: 30000,
|
|
connectionTimeoutMillis: 2000,
|
|
})
|
|
|
|
// 测试连接
|
|
pool.on('connect', () => {
|
|
console.log('✅ Database connected')
|
|
})
|
|
|
|
pool.on('error', (err) => {
|
|
console.error('❌ Unexpected database error:', err)
|
|
})
|
|
|
|
export default pool
|
|
|
|
// 用户接口
|
|
export interface User {
|
|
id: number
|
|
name: string
|
|
email: string
|
|
password: string
|
|
email_verified: boolean
|
|
created_at: Date
|
|
updated_at: Date
|
|
}
|
|
|
|
// 数据库查询函数
|
|
export const db = {
|
|
// 根据邮箱查找用户
|
|
async findUserByEmail(email: string): Promise<User | null> {
|
|
const result = await pool.query(
|
|
'SELECT * FROM users WHERE email = $1',
|
|
[email]
|
|
)
|
|
return result.rows[0] || null
|
|
},
|
|
|
|
// 根据ID查找用户
|
|
async findUserById(id: number): Promise<User | null> {
|
|
const result = await pool.query(
|
|
'SELECT * FROM users WHERE id = $1',
|
|
[id]
|
|
)
|
|
return result.rows[0] || null
|
|
},
|
|
|
|
// 创建新用户
|
|
async createUser(
|
|
name: string,
|
|
email: string,
|
|
password: string
|
|
): Promise<User> {
|
|
const result = await pool.query(
|
|
'INSERT INTO users (name, email, password, email_verified, created_at, updated_at) VALUES ($1, $2, $3, $4, NOW(), NOW()) RETURNING *',
|
|
[name, email, password, false]
|
|
)
|
|
return result.rows[0]
|
|
},
|
|
|
|
// 更新用户
|
|
async updateUser(id: number, data: Partial<User>): Promise<User> {
|
|
const fields = []
|
|
const values = []
|
|
let index = 1
|
|
|
|
if (data.name !== undefined) {
|
|
fields.push(`name = $${index++}`)
|
|
values.push(data.name)
|
|
}
|
|
if (data.email !== undefined) {
|
|
fields.push(`email = $${index++}`)
|
|
values.push(data.email)
|
|
}
|
|
if (data.password !== undefined) {
|
|
fields.push(`password = $${index++}`)
|
|
values.push(data.password)
|
|
}
|
|
if (data.email_verified !== undefined) {
|
|
fields.push(`email_verified = $${index++}`)
|
|
values.push(data.email_verified)
|
|
}
|
|
|
|
fields.push(`updated_at = NOW()`)
|
|
values.push(id)
|
|
|
|
const query = `UPDATE users SET ${fields.join(', ')} WHERE id = $${index} RETURNING *`
|
|
const result = await pool.query(query, values)
|
|
return result.rows[0]
|
|
},
|
|
|
|
// 删除用户
|
|
async deleteUser(id: number): Promise<boolean> {
|
|
const result = await pool.query('DELETE FROM users WHERE id = $1', [id])
|
|
return (result.rowCount ?? 0) > 0
|
|
},
|
|
|
|
// 获取所有用户(用于管理)
|
|
async getAllUsers(): Promise<User[]> {
|
|
const result = await pool.query(
|
|
'SELECT id, name, email, email_verified, created_at FROM users ORDER BY created_at DESC'
|
|
)
|
|
return result.rows
|
|
},
|
|
}
|
|
|