Skip to content

Commit

Permalink
feat: 增加通用的连接成功失败handler
Browse files Browse the repository at this point in the history
  • Loading branch information
ddiu8081 committed Sep 26, 2022
1 parent c321d4a commit 48bfce9
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
48 changes: 47 additions & 1 deletion README.md
Expand Up @@ -32,7 +32,9 @@ const handler: MsgHandler = {
},
}

startListen(652581, handler)
const instance = startListen(652581, handler)

instance.close()
```

## Handlers & Type Definitions
Expand Down Expand Up @@ -88,6 +90,50 @@ export interface User {
}
```

### handler.onOpen

连接成功

```ts
export type Handler = {
/** 连接成功 */
onOpen: () => void,
}
```
### handler.onClose
连接关闭
```ts
export type Handler = {
/** 连接成功 */
onClose: () => void,
}
```
### handler.onError
连接错误
```ts
export type Handler = {
/** 连接错误 */
onError: (e: Error) => void,
}
```
### handler.onStartListen
开始监听消息
```ts
export type Handler = {
/** 开始监听消息 */
onStartListen: () => void,
}
```
### handler.onIncomeDanmu
收到普通弹幕消息
Expand Down
27 changes: 27 additions & 0 deletions src/listener/index.ts
Expand Up @@ -11,6 +11,16 @@ import type { Message } from '../types/app'
import type { KeepLiveTCP } from 'bilibili-live-ws'

export type MsgHandler = Partial<
{
/** 连接成功 */
onOpen: () => void,
/** 连接关闭 */
onClose: () => void,
/** 连接错误 */
onError: (e: Error) => void,
/** 开始监听消息 */
onStartListen: () => void,
}
& AttentionChangeMsgHandler
& DanmuMsgHandler
& GuardBuyHandler
Expand All @@ -36,6 +46,23 @@ const normalizeDanmu = <T>(msgType: string, body: T): Message<T> => {
export const listenAll = (instance: KeepLiveTCP, roomId: number, handler?: MsgHandler) => {
if (!handler) return

// Common
if (handler.onOpen) {
instance.on('open', () => {
handler.onOpen?.()
})
}
if (handler.onClose) {
instance.on('close', () => {
handler.onClose?.()
})
}
if (handler.onStartListen) {
instance.on('live', () => {
handler.onStartListen?.()
})
}

// HEARTBEAT
if (handler[HEARTBEAT.handlerName]) {
instance.on(HEARTBEAT.eventName, (data: any) => {
Expand Down

0 comments on commit 48bfce9

Please sign in to comment.