generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 7
/
db.ts
93 lines (78 loc) · 2.52 KB
/
db.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Low } from 'lowdb';
import { getAppInstance } from 'main';
import { App, Notice, Vault } from 'obsidian';
import { CardSchedule, scheduleData } from 'schedule';
export const DBNAME = 'aosr.db'
export const DBPATH = '.obsidian/'
// 存储文档的数据结构
export interface CardDoc {
ID: string;
CardSchedules: scheduleData[];
}
class ObsidianAdapter {
private basePath: string;
private fileName: string;
constructor(basePath: string, fileName: string) {
this.basePath = basePath;
this.fileName = fileName;
}
async read() {
try {
const filePath = this.basePath + this.fileName;
if (await getAppInstance().vault.adapter.exists(filePath)) {
const data = await getAppInstance().vault.adapter.read(filePath);
return JSON.parse(data);
}
return { docs: [] } as Data;
} catch (error) {
new Notice(`[Aosr] read error: ${error}`);
}
}
async write(data: any) {
const filePath = this.basePath + this.fileName;
const content = JSON.stringify(data);
await getAppInstance().vault.adapter.write(filePath, content);
}
}
type Data = {
docs: CardDoc[];
}
export class DatabaseHelper {
private static instance: DatabaseHelper;
private db: Low<Data>;
public static getInstance(): DatabaseHelper {
if (!DatabaseHelper.instance) {
DatabaseHelper.instance = new DatabaseHelper(DBNAME);
}
return DatabaseHelper.instance;
}
constructor(dbPath: string) {
const adapter = new ObsidianAdapter(DBPATH, dbPath);
this.db = new Low(adapter, {});
this.init();
}
private async init() {
await this.db.read();
if (!this.db.data.docs) {
this.db.data.docs = [];
await this.db.write();
}
}
public insertOrUpdate(cardID: string, cardSchedule: CardSchedule) {
let doc = this.db.data.docs.find((pattern) => pattern.ID === cardID);
if (doc) {
doc.CardSchedules = cardSchedule.cardScheduleToPatternData();
} else {
this.db.data.docs.push({ ID: cardID, CardSchedules: cardSchedule.cardScheduleToPatternData() });
}
}
public query(cardID: string): CardDoc | null {
if (!this.db.data.docs) {
return null;
}
return this.db.data.docs.find((pattern) => pattern.ID === cardID) || null;
}
public async commit() {
await this.db.write();
}
}