XuqmGroup-RNSDK/packages/push/src/PushSDK.ts
XuqmGroup 9e11a63144 feat(sdk): 更新 SDK 设计文档和 API 重构
- 添加 expiresAt 和 refreshUserSig 参数支持自动续签
- 修改 PushSDK 初始化方式,自动完成设备注册和厂商初始化
- 调整过期续签策略,从提前 15 分钟改为提前 5 分钟触发
- 重构 RN SDK 文档结构,简化安装和使用方式
- 更新统一登录流程,支持 profile 信息传递
- 添加 IM 数据库自动隔离功能
- 修复 Android 群消息聚合问题
- 补充自动化测试验证和错误处理机制
2026-05-01 21:27:39 +08:00

92 行
2.7 KiB
TypeScript

import { apiRequest, getConfig, getDeviceInfo, getUserId as getCommonUserId } from '@xuqm/rn-common'
import type { PushVendor } from '@xuqm/rn-common'
export type { PushVendor }
type PendingDeviceToken = {
token: string
vendor?: PushVendor
}
let currentUserId: string | null = null
let pendingToken: PendingDeviceToken | null = null
async function registerPendingToken(): Promise<void> {
const userId = currentUserId ?? getCommonUserId()
if (!userId || !pendingToken) return
const device = await getDeviceInfo()
const config = getConfig()
await apiRequest('/api/push/register', {
method: 'POST',
params: {
appId: config.appId,
userId,
vendor: pendingToken.vendor ?? device.pushVendor,
token: pendingToken.token,
platform: device.platform,
deviceId: device.deviceId,
brand: device.brand,
model: device.model,
osVersion: device.osVersion,
},
})
}
export const PushSDK = {
async initialize(userId?: string): Promise<void> {
currentUserId = userId ?? getCommonUserId()
await registerPendingToken()
},
async setDeviceToken(token: string, vendor?: PushVendor): Promise<void> {
pendingToken = { token, vendor }
await registerPendingToken()
},
/**
* Register a push device token for the given user.
* If vendor is omitted, it is auto-detected from the device brand.
*
* @param userId - The logged-in user's ID
* @param token - The device push token from the vendor SDK
* @param vendor - Optional; auto-detected when not provided
*/
async registerToken(userId: string, token: string, vendor?: PushVendor): Promise<void> {
currentUserId = userId
pendingToken = { token, vendor }
const config = getConfig()
const device = await getDeviceInfo()
await apiRequest('/api/push/register', {
method: 'POST',
params: {
appId: config.appId,
userId,
vendor: vendor ?? device.pushVendor,
token,
platform: device.platform,
deviceId: device.deviceId,
brand: device.brand,
model: device.model,
osVersion: device.osVersion,
},
})
},
async unregisterToken(userId: string): Promise<void> {
const config = getConfig()
const { deviceId } = await getDeviceInfo()
await apiRequest('/api/push/unregister', {
method: 'DELETE',
params: { appId: config.appId, userId, deviceId },
})
if (currentUserId === userId) currentUserId = null
if (pendingToken && currentUserId === null) pendingToken = null
},
async logout(userId?: string): Promise<void> {
const targetUserId = userId ?? currentUserId ?? getCommonUserId()
if (!targetUserId) return
await PushSDK.unregisterToken(targetUserId)
},
}