useOshiStore.ts (2862B)
1 import { ref } from 'vue'; 2 import localforage from 'localforage'; 3 4 // ----------------------------------------------------- 5 // localForageのインスタンス(DB)を先に定義します 6 // 'backgroundStore' という名前のDB(テーブル)を使います 7 // ----------------------------------------------------- 8 const imageStore = localforage.createInstance({ 9 name: 'oshiAppDB', // データベース名 10 storeName: 'oshiStore' // このストアには背景画像を保存 11 }); 12 13 // ----------------------------------------------------- 14 // アプリ全体で共有する「状態」 15 // ----------------------------------------------------- 16 // ギャラリーの画像リスト(最初は空) 17 const oshiList = ref<Array<{ id: string; data: unknown }>>([]); 18 19 // ----------------------------------------------------- 20 // このコンポーザブル(機能)を呼び出すためのメイン関数 21 // ----------------------------------------------------- 22 export function useOshiGallery() { 23 24 /** 25 * DBからすべての画像を読み込み、galleryListを更新する 26 */ 27 const loadOshiImages = async () => { 28 const keys = await imageStore.keys(); 29 const images: Array<{ id: string; data: unknown }> = []; 30 for (const key of keys) { 31 const imageData = await imageStore.getItem(key); 32 // ここでは簡略化のためキーとデータのみ保存 33 images.push({ id: key, data: imageData }); 34 } 35 oshiList.value = images; 36 console.log('ギャラリーを読み込みました:', oshiList.value); 37 }; 38 39 /** 40 * 新しい画像をDBに追加する 41 * @param {Blob} imageBlob - 保存する画像データ 42 */ 43 const addOshiImage = async (imageBlob: Blob) => { 44 // IDとして現在時刻のタイムスタンプを使う(簡易的) 45 const imageId = `img_${Date.now()}`; 46 47 try { 48 await imageStore.setItem(imageId, imageBlob); 49 console.log('画像を追加しました:', imageId); 50 // 保存後、ギャラリーリストを再読み込み 51 await loadOshiImages(); 52 } catch (err) { 53 console.error('画像の保存に失敗:', err); 54 // ここで容量オーバーなどのエラー処理を将来的に追加 55 } 56 }; 57 58 /** 59 * 画像をDBから削除する 60 * @param {String} imageId - 削除する画像のID 61 */ 62 const deleteOshiImage = async (imageId: string) => { 63 try { 64 await imageStore.removeItem(imageId); 65 console.log('画像を削除しました:', imageId); 66 // 削除後、ギャラリーリストを再読み込み 67 await loadOshiImages(); 68 } catch (err) { 69 console.error('画像の削除に失敗:', err); 70 } 71 }; 72 73 // 外部のコンポーネントが使えるように、関数と状態を返す 74 return { 75 oshiList, 76 loadOshiImages, 77 addOshiImage, 78 deleteOshiImage 79 }; 80 }