Update VaultQueryHandler.ts with 3 attempts-write
This commit is contained in:
parent
44d996e7a4
commit
18af4e7d47
|
|
@ -273,16 +273,10 @@ export class VaultQueryHandler {
|
|||
frontmatter: Record<string, any>,
|
||||
body: string
|
||||
): Promise<WriteResult> {
|
||||
const file = this.app.vault.getAbstractFileByPath(path);
|
||||
if (!(file instanceof TFile)) {
|
||||
throw new Error(`Файл не найден для записи: ${path}`);
|
||||
}
|
||||
|
||||
const yamlStr = this._serializeYaml(frontmatter);
|
||||
const newContent = `---\n${yamlStr}---\n\n${body.trim()}\n`;
|
||||
|
||||
await this.app.vault.modify(file, newContent);
|
||||
return { success: true, path };
|
||||
return this._writeFileWithRetry(path, newContent);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
|
@ -297,26 +291,75 @@ export class VaultQueryHandler {
|
|||
path: string,
|
||||
content: string
|
||||
): Promise<WriteResult> {
|
||||
// Создаём папки если нужно
|
||||
const folderPath = path.includes('/')
|
||||
? path.substring(0, path.lastIndexOf('/'))
|
||||
: null;
|
||||
return this._writeFileWithRetry(path, content);
|
||||
}
|
||||
|
||||
if (folderPath) {
|
||||
const folderExists = this.app.vault.getAbstractFileByPath(folderPath);
|
||||
if (!folderExists) {
|
||||
await this.app.vault.createFolder(folderPath);
|
||||
// -------------------------------------------------------------------------
|
||||
// Общий метод записи с повторными попытками
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private async _writeFileWithRetry(
|
||||
path: string,
|
||||
content: string,
|
||||
maxAttempts = 3
|
||||
): Promise<WriteResult> {
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
// --- Шаг 1: Запись ---
|
||||
const existing = this.app.vault.getAbstractFileByPath(path);
|
||||
|
||||
if (existing instanceof TFile) {
|
||||
await this.app.vault.modify(existing, content);
|
||||
} else {
|
||||
// Создать папки при необходимости
|
||||
const folderPath = path.includes('/')
|
||||
? path.substring(0, path.lastIndexOf('/'))
|
||||
: null;
|
||||
if (folderPath) {
|
||||
const folderExists = this.app.vault.getAbstractFileByPath(folderPath);
|
||||
if (!folderExists) {
|
||||
await this.app.vault.createFolder(folderPath);
|
||||
}
|
||||
}
|
||||
await this.app.vault.create(path, content);
|
||||
}
|
||||
|
||||
// --- Шаг 2: Проверка (перечитываем и сравниваем) ---
|
||||
const writtenFile = this.app.vault.getAbstractFileByPath(path);
|
||||
if (!(writtenFile instanceof TFile)) {
|
||||
throw new Error(`Файл не найден сразу после записи: ${path}`);
|
||||
}
|
||||
const writtenContent = await this.app.vault.read(writtenFile);
|
||||
|
||||
// Сравниваем, игнорируя возможные конечные переводы строк
|
||||
if (writtenContent.trim() === content.trim()) {
|
||||
// Успех
|
||||
return { success: true, path };
|
||||
} else {
|
||||
// Содержимое не совпало — ошибка
|
||||
throw new Error(
|
||||
`Содержимое файла не совпадает с записанным (попытка ${attempt})`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
console.warn(
|
||||
`VaultQueryHandler: попытка ${attempt} записи ${path} не удалась:`,
|
||||
lastError.message
|
||||
);
|
||||
if (attempt < maxAttempts) {
|
||||
// Экспоненциальная задержка: 100, 200, 300 мс
|
||||
const delay = 100 * attempt;
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const existing = this.app.vault.getAbstractFileByPath(path);
|
||||
if (existing instanceof TFile) {
|
||||
await this.app.vault.modify(existing, content);
|
||||
} else {
|
||||
await this.app.vault.create(path, content);
|
||||
}
|
||||
|
||||
return { success: true, path };
|
||||
throw new Error(
|
||||
`Не удалось записать файл ${path} после ${maxAttempts} попыток: ${lastError?.message || 'неизвестная ошибка'}`
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user