XuqmGroup-RNSDK/src/im/imSDK.ts

95 行
2.5 KiB
TypeScript

2026-04-21 22:07:29 +08:00
import { getConfig } from '../core/config'
import { apiRequest, getToken, saveToken } from '../core/http'
2026-04-21 22:07:29 +08:00
import { ImClient } from './imClient'
import type { ChatType, ImEventListener, ImMessage, MsgType } from './types'
2026-04-21 22:07:29 +08:00
let client: ImClient | null = null
export const ImSDK = {
async login(userId: string, nickname?: string, avatar?: string): Promise<void> {
const config = getConfig()
const res = await apiRequest<{ token: string }>('/api/im/auth/login', {
method: 'POST',
params: {
appId: config.appId,
userId,
...(nickname ? { nickname } : {}),
...(avatar ? { avatar } : {}),
},
})
await saveToken(res.token)
client = new ImClient(config.imWsUrl, res.token, config.appId)
client.connect()
},
async reconnect(): Promise<void> {
const config = getConfig()
const token = await getToken()
if (!token) throw new Error('ImSDK: token not found')
client = new ImClient(config.imWsUrl, token, config.appId)
client.connect()
},
async fetchHistory(toId: string, page = 0, size = 20): Promise<ImMessage[]> {
const config = getConfig()
const res = await apiRequest<{ content?: ImMessage[] } | ImMessage[]>(`/api/im/messages/history/${encodeURIComponent(toId)}`, {
params: {
appId: config.appId,
page: String(page),
size: String(size),
},
})
return Array.isArray(res) ? res : (res.content ?? [])
},
async sendMessage(
toId: string,
chatType: ChatType,
msgType: MsgType,
content: string,
mentionedUserIds?: string,
): Promise<ImMessage> {
const config = getConfig()
return apiRequest<ImMessage>('/api/im/messages/send', {
method: 'POST',
params: { appId: config.appId },
body: {
toId,
chatType,
msgType,
content,
mentionedUserIds: mentionedUserIds ?? '',
},
})
},
async revokeMessage(messageId: string): Promise<ImMessage> {
const config = getConfig()
return apiRequest<ImMessage>(`/api/im/messages/${encodeURIComponent(messageId)}/revoke`, {
method: 'POST',
params: { appId: config.appId },
})
2026-04-21 22:07:29 +08:00
},
addListener(listener: ImEventListener) {
client?.addListener(listener)
},
removeListener(listener: ImEventListener) {
client?.removeListener(listener)
},
disconnect() {
client?.disconnect()
client = null
},
subscribeGroup(groupId: string) {
client?.subscribeGroup(groupId)
},
2026-04-21 22:07:29 +08:00
isConnected() {
return client?.isConnected() ?? false
},
}