mcpField
M
mobile-offline-support

mobile-offline-support

github.com/secondsky開発242406 回インストール5 週間前に更新
リポジトリ

mobile-offline-support について

オフラインファーストのモバイルアプリを開発する人向けのスキルです。React Native の例と iOS・Android ネイティブ実装の参考情報を含み、ローカルデータ、同期、競合処理を扱います。

主な機能

  1. 01ローカルデータのキャッシュ
  2. 02後で同期する操作のキューイング
  3. 03接続状態インジケーター
  4. 04同期時の競合処理
  5. 05iOS と Android のネイティブ実装資料

活用シーン

  1. 01ネットワーク接続なしでのアプリ利用
  2. 02再接続後のキュー済み変更の同期
  3. 03ローカルとサーバー間の更新競合への対応
  4. 04現在の接続状態のユーザーへの表示

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/secondsky/claude-skills --skill mobile-offline-support

インストール後、Claude Code で/mobile-offline-supportを入力して読み込まれたか確認します。

同梱ファイルreferences/native-implementations.md

詳細

モバイルのオフライン対応

ローカルストレージと同期を活用して、オフライン優先のモバイルアプリケーションを構築します。

React Native の実装

import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';

class OfflineManager {
  constructor() {
    this.syncQueue = [];
    this.isOnline = true;
    // Maximum items in sync queue before discarding oldest
    this.MAX_SYNC_QUEUE_LENGTH = 1000;

    NetInfo.addEventListener(state => {
      this.isOnline = state.isConnected;
      if (this.isOnline) this.processQueue();
    });
  }

  /**
   * Fetch data from server.
   * TODO: Replace with actual API endpoint implementation.
   */
  async fetchFromServer(key) {
    try {
      // Example implementation - replace with your API
      const response = await fetch(`${API_BASE_URL}/data/${key}`);
      if (!response.ok) {
        throw new Error(`Server returned ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('fetchFromServer failed:', error);
      throw new Error(`Failed to fetch ${key}: ${error.message}`);
    }
  }

  /**
   * Sync data to server.
   * TODO: Replace with actual API endpoint implementation.
   */
  async syncToServer(key, data) {
    try {
      // Example implementation - replace with your API
      const response = await fetch(`${API_BASE_URL}/data/${key}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });
      if (!response.ok) {
        throw new Error(`Server returned ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('syncToServer failed:', error);
      throw new Error(`Failed to sync ${key}: ${error.message}`);
    }
  }

  async getData(key) {
    const cached = await AsyncStorage.getItem(key);
    if (cached) return JSON.parse(cached);

    if (this.isOnline) {
      const data = await this.fetchFromServer(key);
      await AsyncStorage.setItem(key, JSON.stringify(data));
      return data;
    }

    return null;
  }

  async saveData(key, data) {
    await AsyncStorage.setItem(key, JSON.stringify(data));

    if (this.isOnline) {
      await this.syncToServer(key, data);
    } else {
      // Add to queue
      this.syncQueue.push({ key, data, timestamp: Date.now() });

      // Enforce queue bounds - discard oldest if exceeded
      while (this.syncQueue.length > this.MAX_SYNC_QUEUE_LENGTH) {
        const discarded = this.syncQueue.shift();
        console.warn(`Sync queue full - discarded oldest item: ${discarded.key}`);
      }

      // Persist trimmed queue
      await AsyncStorage.setItem('syncQueue', JSON.stringify(this.syncQueue));
    }
  }

  async processQueue() {
    const failedItems = [];
    for (const item of this.syncQueue) {
      try {
        await this.syncToServer(item.key, item.data);
      } catch (err) {
        console.error('Sync failed:', err);
        failedItems.push(item);
      }
    }
    this.syncQueue = failedItems;
    if (failedItems.length === 0) {
      await AsyncStorage.removeItem('syncQueue');
    } else {
      await AsyncStorage.setItem('syncQueue', JSON.stringify(failedItems));
    }
  }
}

競合の解決

function resolveConflict(local, server) {
  // Last-write-wins
  if (local.updatedAt > server.updatedAt) return local;
  return server;

  // Or merge changes
  // return { ...server, ...local };
}

UI インジケーター

function OfflineIndicator() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    return NetInfo.addEventListener(state => {
      setIsOnline(state.isConnected);
    });
  }, []);

  if (isOnline) return null;

  return (
    <View style={styles.banner}>
      <Text>You're offline. Changes will sync when connected.</Text>
    </View>
  );
}

ベストプラクティス

  • 頻繁にアクセスするデータをローカルにキャッシュします
  • 後で同期するアクションをキューに追加します
  • オフライン状態を明確に表示します
  • 同期の競合を適切に処理します
  • 保存データを圧縮します
  • オフラインのシナリオを十分にテストします

ネイティブ実装

以下を参照してください:references/native-implementations.md

  • 同期マネージャーを備えた iOS Core Data
  • WorkManager による同期を備えた Android Room データベース

避けるべきこと

  • 接続があると仮定すること
  • 同期の失敗時にデータを失うこと
  • キューが際限なく増加すること
  • 機密データを安全でない方法で同期すること

コメント