Skip to content

Commit 00dac86

Browse files
committed
投稿更新用のイベントハンドラーを追加
1 parent ab9d372 commit 00dac86

File tree

1 file changed

+52
-9
lines changed

1 file changed

+52
-9
lines changed

src/commands/openItem.ts

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,71 @@
11
import * as fs from 'fs';
22
import { Item } from 'qiita-js-2';
3-
import { Uri, window, workspace } from 'vscode';
3+
import { TextDocument, Uri, window, workspace } from 'vscode';
44
import * as nls from 'vscode-nls';
5+
import { client } from '../client';
6+
import { handleErrorMessage } from '../utils/errorHandler';
57

68
const localize = nls.loadMessageBundle();
79

10+
/**
11+
* ワークスペース内でQiitaから同期したファイルを保存したときに呼ばれるイベントリスナ
12+
* @param item 投稿の元データ
13+
* @param document 保存されたドキュメント
14+
*/
15+
export const updater = async (item: Item, document: TextDocument) => {
16+
const body = document.getText();
17+
18+
if (body === item.body) {
19+
return;
20+
}
21+
22+
try {
23+
await client.updateItem(item.id, {
24+
title: item.title,
25+
tags: item.tags,
26+
body,
27+
});
28+
29+
fs.writeFileSync(document.uri.path, document.getText());
30+
31+
window.showInformationMessage('updated');
32+
} catch (error) {
33+
handleErrorMessage(error);
34+
}
35+
};
36+
37+
/**
38+
* アイテムを開くコマンドハンドラーを返す関数
39+
* @param storagePath 拡張機能のストレージのpath
40+
*/
841
export function openItem (storagePath?: string) {
942
return async (item: Item) => {
10-
try {
11-
const filePath = `${storagePath}/${item.id}.md`;
12-
const fileUri = `file://${filePath}`;
43+
if (!storagePath) {
44+
return;
45+
}
1346

14-
if (!storagePath) {
15-
return;
16-
}
47+
try {
48+
const fileUri = Uri.parse(`file://${storagePath}/${item.id}.md`);
1749

50+
// 拡張機能用ディレクトリがない場合初期化
1851
if (!fs.existsSync(storagePath)) {
1952
fs.mkdirSync(storagePath);
2053
}
2154

22-
fs.writeFileSync(filePath, item.body);
55+
// まだファイルをローカルに保存していない場合初期化
56+
if (!fs.existsSync(fileUri.fsPath)) {
57+
fs.writeFileSync(fileUri.fsPath, item.body);
58+
}
2359

24-
const document = await workspace.openTextDocument(Uri.parse(fileUri));
60+
const document = await workspace.openTextDocument(fileUri);
2561
await window.showTextDocument(document);
62+
63+
// 保存時にアップデートするためのイベントリスナを追加
64+
workspace.onDidSaveTextDocument(async (updatedDocument) => {
65+
if (updatedDocument.uri.path === fileUri.path) {
66+
await updater(item, updatedDocument);
67+
}
68+
});
2669
} catch (error) {
2770
window.showErrorMessage(localize(
2871
'commands.openItem.failure.fallback',

0 commit comments

Comments
 (0)