refactor: migrate entire project to TypeScript
This commit is contained in:
49
utils/database.ts
Normal file
49
utils/database.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
|
||||
class DatabaseWrapper {
|
||||
private db: Database.Database;
|
||||
private dbPath: string;
|
||||
|
||||
constructor() {
|
||||
this.dbPath = process.env.DB_PATH || path.join(__dirname, '../data/database.sqlite');
|
||||
this.db = new Database(this.dbPath, { verbose: console.log });
|
||||
}
|
||||
|
||||
get<T = any>(sql: string, params: any[] = []): T | undefined {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.get(params) as T | undefined;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
all<T = any>(sql: string, params: any[] = []): T[] {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
return stmt.all(params) as T[];
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
run(sql: string, params: any[] = []): { id: number; changes: number } {
|
||||
try {
|
||||
const stmt = this.db.prepare(sql);
|
||||
const result = stmt.run(params);
|
||||
return { id: result.lastInsertRowid as number, changes: result.changes };
|
||||
} catch (error) {
|
||||
console.error('数据库操作错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export default new DatabaseWrapper();
|
||||
Reference in New Issue
Block a user