How sunnylqm/react-native-storage works
Project type and purpose
• This is an open‑source JavaScript library called “react‑native‑storage.”
• Purpose: A unified wrapper around React Native’s AsyncStorage and the browser’s localStorage.
• Key features: promise‑based API, in‑memory caching, LRU‑style size limit, expiration, and user‑defined sync methods for auto‑refreshing missing or expired data.
File structure
• Top‑level config:
• package.json, babel.config.js, rollup.config.js → build & publish pipeline (ES6→commonjs/browser bundles).
• .travis.yml, tea.yaml → CI & release.
• Source:
• src/storage.js (.d.ts) → core Storage class.
• src/error.js → custom Error types (NotFoundError, ExpiredError).
• Tests:
• __tests__ + jestSupport/mockStorage.js → Jest‑based unit tests, mocking AsyncStorage/localStorage.
• No “frontend” or “backend” folders—this is a library module, not an application.
Architecture hints from README
• Describes a Storage constructor that accepts a “storageBackend” adapter (AsyncStorage or window.localStorage).
• In‑memory caching (enableCache).
• Expiration logic + autoSync hooks (user‑supplied functions under storage.sync).
• Batch loading methods with per‑key or per‑key‑with‑ids strategies.
a. Main components
1. Consumer Application (React Native app or Web app)
2. Storage Facade (the “Storage” class)
3. In‑Memory Cache (optional, controlled by enableCache)
4. Persistent Backend Adapter
– AsyncStorageAdapter (RN)
– LocalStorageAdapter (Web)
5. Expiration & LRU Manager (size limit, defaultExpires)
6. Sync Manager (user‑provided sync.* functions)
7. Error Module (custom errors thrown to caller)
8. Build & Test Pipeline (Babel → Rollup; Jest + mockStorage)
b. Relationships & data flow
1. App invokes Storage.save / load / remove / getBatchData.
2. Storage first checks In‑Memory Cache (hit? return).
3. Else calls Persistent Backend Adapter.
4. Adapter returns raw data + meta (timestamp, expires).
5. Expiration & LRU Manager decides if data is stale or map size exceeded.
– If stale or missing and autoSync enabled → call Sync Manager.
6. Sync Manager invokes user’s storage.sync[key]() or batch function.
7. New data flows into Storage.save, updating Cache + Adapter.
8. Any time an error occurs → throw custom Error from Error Module → bubbled to App.
c. Architectural patterns & principles
• Facade pattern: Single unified Storage API.
• Adapter pattern: Abstracts underlying storage (AsyncStorage vs localStorage).
• Strategy pattern: Plug‑in sync methods.
• Separation of concerns: caching, persistence, expiry, sync logic are modular.
• Promise‑based async flows (no callbacks).
d. Key technologies & libraries
• JavaScript ES6 modules (babel.config.js)
• Rollup bundler (rollup.config.js) for multiple targets (CJS, ESM, UMD)
• Jest + jestSupport/mockStorage.js for unit testing
• AsyncStorage (@react‑native‑async‑storage/async‑storage)
• Browser window.localStorage