generated from tpl/obsidian-sample-plugin
48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import BookTrackerPlugin from "@src/main";
|
|
import { App, normalizePath } from "obsidian";
|
|
|
|
export class Storage {
|
|
public constructor(
|
|
private readonly app: App,
|
|
private readonly plugin: BookTrackerPlugin
|
|
) {}
|
|
|
|
private readonly baseDir = this.plugin.manifest.dir!;
|
|
private getFilePath(filename: string): string {
|
|
return normalizePath(`${this.baseDir}/${filename}`.replace(/\/$/, ""));
|
|
}
|
|
|
|
public async readJSON<T>(filename: string): Promise<T | null> {
|
|
const filePath = this.getFilePath(filename);
|
|
const content = await this.app.vault.adapter.read(filePath);
|
|
if (!content) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
return JSON.parse(content) as T;
|
|
} catch (error) {
|
|
console.error(`Error parsing JSON from ${filePath}:`, error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async writeJSON<T>(filename: string, data: T): Promise<void> {
|
|
const filePath = this.getFilePath(filename);
|
|
const content = JSON.stringify(data, null, 2);
|
|
await this.app.vault.adapter.write(filePath, content);
|
|
}
|
|
|
|
public async listFiles(subdir = ""): Promise<string[]> {
|
|
const files = await this.app.vault.adapter.list(
|
|
this.getFilePath(subdir)
|
|
);
|
|
return files.files;
|
|
}
|
|
|
|
public async listFolders(): Promise<string[]> {
|
|
const files = await this.app.vault.adapter.list(this.baseDir);
|
|
return files.folders;
|
|
}
|
|
}
|