refactor: migrate backend framework from Express to NestJS

This commit is contained in:
2026-02-07 01:45:53 +08:00
parent 2c006c3330
commit 1eb8abb447
31 changed files with 6052 additions and 995 deletions

View File

@@ -0,0 +1,59 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Database from 'better-sqlite3';
import * as path from 'path';
import * as fs from 'fs';
@Injectable()
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
private db: Database.Database;
private dbPath: string;
constructor(private configService: ConfigService) {}
onModuleInit() {
this.dbPath = this.configService.get<string>('DB_PATH', path.join(process.cwd(), 'data/database.sqlite'));
const dbDir = path.dirname(this.dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
this.db = new Database(this.dbPath, { verbose: console.log });
}
onModuleDestroy() {
this.db.close();
}
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;
}
}
}