1.0.9 • Published 4 years ago
trap-client-sdk v1.0.9
trap-client-sdk
Trap push server JavaScript SDK.
- 简单易用
- 提供 React Hook API
📦 安装
npm i trap-client-sdk --save
🔨使用
基础 API
import { TrapClient } from 'trap-client-sdk'
const trapClient = new TrapClient(async () => {
const { token, endpoint } = await fetch('/getTrapToken').then(resp => resp.json())
return {
// appId 必填
appId: 1,
// server URL 必填
serverUrl: endpoint,
// 连接凭证 必填
token,
// 是否显示 debug 信息 默认 false
debug: false,
// 自动重连时间 毫秒数 默认 1000
reconnectInterval: 1000,
// 重连时间衰减因子 第 n 次重连的时间等于 Math.pow(reconnectDecay, n) * reconnectInterval 默认 1.5
reconnectDecay: 1.5,
// 连接超时时间 毫秒数 默认 2000
timeoutInterval: 2000,
// 最大重试次数 -1 表示无限重试 默认 -1
maxReconnectAttempts: -1,
// 响应超时时间 默认 3000
responseTimeout: 3000,
};
})
trapClient.once('ready', () => {
function room1Listener(msg) => {
console.log('room1', msg)
}
trapClient.onMessage('room1', room1Listener)
trapClient.onBroadcast((msg) => {
console.log('广播消息', msg)
})
// 移除事件监听
// trapClient.removeMessageListener('room1', listener)
})
如果你使用 React Hook
import React, { createContext, Fragment } from 'react'
import { TrapProvider, useTrapReady, useTrapMsgList, useTrapEvent, useTrapEventFn, deserialize } from 'trap-client-sdk'
const TrapContext = createContext()
function App() {
return (
// TrapProvider 放到所有使用 trap hook 的组件的根组件上
<TrapProvider Context={TrapContext} deserializeFn={deserialize.json()} option={async () => {
const { token, endpoint } = await fetch('/getTrapToken').then(resp => resp.json())
// 返回 配置对象 配置详情见基础 API
return { serverUrl: endpoint, appId: 1, debug: true, token }
}} onAfterDisConnect={(trapClient) => {
// 当与服务器断开连接 重新连接
setTimeout(() => {trapClient.reConnect()}, 3000)
}}>
<Room />
</TrapProvider>
)
}
function Room({ key }) {
// 如果 trap client 已经初始化完成 ready 为 true
const ready = useTrapReady(TrapContext)
// 订阅一个 key 返回一个消息数组
const msgList = useTrapMsgList(TrapContext, key)
// 订阅一个 key 每次返回最新的消息
const { count } = useTrapEvent(TrapContext, key + '_count')
const [count1, setCount1] = useState(0)
// 订阅一个key 通过回调函数获取最新消息, cancelFn 用于取消订阅
const cancelFn = useTrapEventFn(TrapContext, key + '_count1', (e) => {
setCount1(e.body)
})
if (!ready) {
return <div>Loading...</div>
} else {
return (
<Fragment>
<h1>count: {count}</h1>
<h1>count1: {count1}</h1>
<ul>{msgList.map(msg => <li>{msg}</li>)}</ul>
</Fragment>
)
}
}
🤝 参与贡献
$ git clone https://gitlab.weilaijishi.net/trap/sdk.git
$ cd sdk/client-js
$ npm i
$ npm start
// ...Doing some awesome work.
// Send merge request.