如何使用 `apollo-cache-persist` 搭配 `react-native-sqlite-storage`?
解读
国内 React Native 项目普遍对“离线可用、弱网恢复、启动白屏时间”有硬性 KPI。面试官问这道题,不是让你背 API,而是想看三件事:
- 你是否理解 Apollo 缓存的“内存+持久化”双层架构;
- 你是否能在 Native 端选择真正稳定、可灰度、可回滚的存储引擎(AsyncStorage 在 60 万条记录时性能雪崩,SQLite 才是国内生产环境的主流);
- 你是否能把“缓存恢复”做成可观测、可降级、可热切换的环节,而不是一次性的 demo 代码。
一句话:这道题考察的是“高日活场景下的数据层可用性设计能力”。
知识点
- apollo-cache-persist 的抽象层:PersistentStorage 接口只要求
getItem/setItem/removeItem,并不要求一定是 AsyncStorage。 - react-native-sqlite-storage 返回的是 Promise,而 apollo-cache-persist 内部用
await storage.getItem(key),所以必须做一层“Promise 包装同步化”或“异步批处理”。 - 缓存上限策略:国内 4G 低端机占比仍高,微信、支付宝小程序共存,bundle 体积敏感,必须设置 maxSize(默认 1 MB)+自定义 trigger(count-based 或 time-based)。
- 恢复失败降级:SQLite 文件损坏、用户手动清缓存、升级数据库版本失败,都要能降级到“空缓存重新拉取”,并上报 SLS/Sentry。
- 多实例隔离:灰度包、正式包、小程序内嵌 RN 页面,需要按
cacheKeyPrefix隔离,防止缓存穿透。 - 加密合规:国内《个人信息保护法》要求敏感数据加密存储,SQLite 层需接入 SQLCipher,但 SQLCipher 体积 +3.5 MB,要在 CI 做 flavor 区分。
答案
下面给出可直接落地的“三件套”代码,覆盖初始化、存储适配、灰度降级、加密、性能监控,面试官若挑刺,可逐条回怼。
- 封装 SQLite 驱动(typescript,单元测试可 mock)
// src/utils/SQLiteCacheAdapter.ts
import SQLite from 'react-native-sqlite-storage';
SQLite.DEBUG(__DEV__);
SQLite.enablePromise(true);
const DB_NAME = 'apollo_cache.db';
const TABLE_NAME = 'cache_store';
class SQLiteCacheAdapter {
private db: SQLite.SQLiteDatabase | null = null;
async init(): Promise<void> {
this.db = await SQLite.openDatabase({
name: DB_NAME,
location: 'default',
createFromLocation: '~www/apollo_cache.db', // 预置空 schema,减少首次建表耗时
});
await this.db.executeSql(
`CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (key TEXT PRIMARY KEY, value TEXT)`
);
}
async getItem(key: string): Promise<string | null> {
if (!this.db) throw new Error('SQLite not initialized');
const [res] = await this.db.executeSql(
`SELECT value FROM ${TABLE_NAME} WHERE key = ? LIMIT 1`,
[key]
);
return res.rows.length ? res.rows.item(0).value : null;
}
async setItem(key: string, value: string): Promise<void> {
if (!this.db) throw new Error('SQLite not initialized');
// REPLACE INTO 保证幂等
await this.db.executeSql(
`REPLACE INTO ${TABLE_NAME} (key, value) VALUES (?, ?)`,
[key, value]
);
}
async removeItem(key: string): Promise<void> {
if (!this.db) throw new Error('SQLite not initialized');
await this.db.executeSql(
`DELETE FROM ${TABLE_NAME} WHERE key = ?`,
[key]
);
}
async clear(): Promise<void> {
if (!this.db) throw new Error('SQLite not initialized');
await this.db.executeSql(`DELETE FROM ${TABLE_NAME}`);
}
async close(): Promise<void> {
if (this.db) {
await this.db.close();
this.db = null;
}
}
}
export const sqliteCacheAdapter = new SQLiteCacheAdapter();
- 初始化 Apollo Client 并接入持久化(含加密、灰度、性能埋点)
// src/apollo/index.ts
import { ApolloClient, InMemoryCache, ApolloLink, HttpLink } from '@apollo/client';
import { persistCache } from 'apollo-cache-persist';
import { sqliteCacheAdapter } from '../utils/SQLiteCacheAdapter';
import * as Sentry from '@sentry/react-native';
import Config from 'react-native-config';
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
// 示例:分页列表合并策略
feed: {
keyArgs: false,
merge(existing = [], incoming) {
return [...existing, ...incoming];
},
},
},
},
},
});
export async function createApolloClient() {
await sqliteCacheAdapter.init();
try {
const before = Date.now();
await persistCache({
cache,
storage: sqliteCacheAdapter as any, // 类型断言,官方允许
maxSize: Config.CACHE_MAX_SIZE ? parseInt(Config.CACHE_MAX_SIZE, 10) : 1024 * 1024,
debug: __DEV__,
trigger: 'background', // 国内低端机用 background,减少用户滑动掉帧
});
const cost = Date.now() - before;
// 性能埋点:>800 ms 报警
if (cost > 800) {
Sentry.captureMessage(`ApolloCacheRestoreSlow:${cost}`);
}
} catch (e) {
// 降级:清空 SQLite 重新拉取
Sentry.captureException(e);
await sqliteCacheAdapter.clear();
}
const httpLink = new HttpLink({
uri: Config.GRAPHQL_ENDPOINT,
headers: {
'X-Client-Version': Config.VERSION_NAME,
},
});
const authLink = new ApolloLink((operation, forward) => {
const token = global.userStore.accessToken; // 全局 mobx/zustand
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : '',
},
});
return forward(operation);
});
const client = new ApolloClient({
cache,
link: authLink.concat(httpLink),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
},
});
return client;
}
- 加密合规(可选,面试提到即可)
若业务涉敏感字段,可在 SQLite 层接入
react-native-sqlite-2+ SQLCipher,只需把openDatabase换成:
SQLite.openDatabase({
name: DB_NAME,
key: 'userSpecificKeyFromKeychain', // 每次启动从 Keychain 取,不落盘
migrate: true,
})
并在 CI 里打两个 flavor:secure / nonSecure,国内商店渠道包体积敏感,nonSecure 包可缩减 3.5 MB。
拓展思考
-
热切换:用户切账号时,如何秒级清空并重建缓存?
答:监听登录态变更事件,调用client.clearStore()后,再执行persistCache.purge()把 SQLite 清掉,避免旧账号数据污染。 -
分片缓存:首页、订单、商品详情三套 GraphQL 服务,如何隔离?
答:建三个 SQLite 文件,或同一文件用keyPrefix隔离,恢复时并发Promise.all,失败单个降级,不影响其他业务。 -
小程序内嵌 RN:微信 WebView 限制 50 MB,如何瘦身?
答:把缓存上限降到 200 KB,只持久化关键字段(userId、token),其余走内存缓存;小程序退出即销毁,减少审计风险。 -
自动化测试:Jest 环境没有 SQLite,如何 mock?
答:用apollo-cache-persist/lib/storageWrappers/InMemoryStorage作为 mock,单元测试跑在 Node 端,集成测试跑在真机,双通道保障。
把以上四点主动抛给面试官,基本锁定 offer。