refactor: migrate database layer to Prisma ORM
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user