- 实现SDKContext用于配置管理和数据持久化存储 - 定义完整的类型系统包括消息、用户、群组等接口 - 集成更新SDK支持原生应用和RN热更新检查 - 提供统一的XuqmSDK入口类和模块导出 - 编写详细的开发文档和使用示例
91 行
2.6 KiB
Plaintext
91 行
2.6 KiB
Plaintext
import preferences from '@ohos.data.preferences'
|
|
import type { InstalledRnBundleInfo, SDKConfig } from './Types'
|
|
|
|
const TOKEN_KEY = 'xuqm_token'
|
|
const RN_BUNDLE_PREFIX = 'xuqm_rn_bundle_'
|
|
const PREF_NAME = 'xuqm_sdk_prefs'
|
|
|
|
export class SDKContext {
|
|
private static _config: SDKConfig | null = null
|
|
private static _token: string | null = null
|
|
private static _userId: string | null = null
|
|
private static _pref: preferences.Preferences | null = null
|
|
|
|
static init(config: SDKConfig): void {
|
|
SDKContext._config = config
|
|
if (config.debug) {
|
|
console.log('[XuqmSDK] init appKey=' + config.appKey)
|
|
}
|
|
}
|
|
|
|
static getConfig(): SDKConfig {
|
|
if (!SDKContext._config) {
|
|
throw new Error('XuqmSDK not initialized. Call XuqmSDK.init() first.')
|
|
}
|
|
return SDKContext._config
|
|
}
|
|
|
|
static async initPreferences(context: Context): Promise<void> {
|
|
SDKContext._pref = await preferences.getPreferences(context, PREF_NAME)
|
|
const saved = await SDKContext._pref.get(TOKEN_KEY, '') as string
|
|
if (saved) SDKContext._token = saved
|
|
}
|
|
|
|
static async setToken(token: string | null): Promise<void> {
|
|
SDKContext._token = token
|
|
if (SDKContext._pref) {
|
|
if (token) {
|
|
await SDKContext._pref.put(TOKEN_KEY, token)
|
|
} else {
|
|
await SDKContext._pref.delete(TOKEN_KEY)
|
|
}
|
|
await SDKContext._pref.flush()
|
|
}
|
|
}
|
|
|
|
static getToken(): string | null {
|
|
return SDKContext._token
|
|
}
|
|
|
|
static setUserId(userId: string | null): void {
|
|
SDKContext._userId = userId
|
|
}
|
|
|
|
static getUserId(): string | null {
|
|
return SDKContext._userId
|
|
}
|
|
|
|
private static rnBundleKey(bundleName: string): string {
|
|
return RN_BUNDLE_PREFIX + bundleName
|
|
}
|
|
|
|
static async setRnBundleInfo(bundleName: string, info: InstalledRnBundleInfo): Promise<void> {
|
|
if (!SDKContext._pref || !bundleName.trim()) {
|
|
return
|
|
}
|
|
const payload = JSON.stringify(info)
|
|
await SDKContext._pref.put(SDKContext.rnBundleKey(bundleName), payload)
|
|
await SDKContext._pref.flush()
|
|
}
|
|
|
|
static async getRnBundleInfo(bundleName: string): Promise<InstalledRnBundleInfo | null> {
|
|
if (!SDKContext._pref || !bundleName.trim()) {
|
|
return null
|
|
}
|
|
const raw = await SDKContext._pref.get(SDKContext.rnBundleKey(bundleName), '') as string
|
|
if (!raw) {
|
|
return null
|
|
}
|
|
try {
|
|
return JSON.parse(raw) as InstalledRnBundleInfo
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
static async getRnBundleVersion(bundleName: string): Promise<number | null> {
|
|
const info = await SDKContext.getRnBundleInfo(bundleName)
|
|
return info?.bundleVersion ?? null
|
|
}
|
|
}
|