refactor: migrate database layer to Prisma ORM

This commit is contained in:
2026-02-07 02:26:00 +08:00
parent 1eb8abb447
commit 2dc6bf16ec
15 changed files with 875 additions and 854 deletions

View File

@@ -1,59 +1,25 @@
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';
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
@Injectable()
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
private db: Database.Database;
private dbPath: string;
private prisma: PrismaClient;
constructor(private configService: ConfigService) {}
constructor() {
this.prisma = new PrismaClient({
log: ["query", "error", "warn"],
});
}
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 });
this.prisma.$connect();
}
onModuleDestroy() {
this.db.close();
this.prisma.$disconnect();
}
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;
}
getPrisma() {
return this.prisma;
}
}