37 lines
1003 B
TypeScript
37 lines
1003 B
TypeScript
// 定义抽象基类
|
||
import Realm from 'realm'
|
||
|
||
export abstract class BaseService {
|
||
protected realm: Realm | null = null
|
||
// 抽象类的构造函数应该是protected,以防止外部直接实例化
|
||
protected constructor() {
|
||
// 构造函数逻辑,使用someValue进行初始化
|
||
}
|
||
|
||
// 定义抽象方法,子类必须实现,打开数据库连接
|
||
abstract open(dbPath: string): void
|
||
|
||
// 关闭数据库连接
|
||
close(): void {
|
||
// 关闭数据库的连接,防止内存溢出
|
||
// 实现关闭数据库连接的逻辑
|
||
if (this.realm != null) {
|
||
console.log('Closing database connection')
|
||
this.realm.close()
|
||
this.realm = null // 清理引用,确保垃圾回收
|
||
}
|
||
}
|
||
transaction(func: () => unknown): void {
|
||
if (this.realm != null) {
|
||
// 判断当前的relam是不是在一个事务中
|
||
if (this.realm.isInTransaction) {
|
||
func()
|
||
} else {
|
||
this.realm.write(() => {
|
||
func()
|
||
})
|
||
}
|
||
}
|
||
}
|
||
}
|