Skip to content
This repository has been archived by the owner on May 23, 2022. It is now read-only.

Commit

Permalink
feat: add connect event
Browse files Browse the repository at this point in the history
  • Loading branch information
pikadun committed May 28, 2021
1 parent 3aef19c commit 96cf2b0
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ See the complete command list: [https://redis.io/commands](https://redis.io/comm

+ `message`: See [Pub/Sub](#Pub/Sub)
+ `error`: Emitted when a connection error occurs.
+ `connect`: Emitted when a socket connection is successfully established.

### Pub/Sub

Expand Down
1 change: 1 addition & 0 deletions doc/zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ client.GET(...args);

+ `message`: 查看 [Pub/Sub](#Pub/Sub)
+ `error`: 发生连接错误时触发。
+ `connect`: 成功建立socket连接时触发。

### Pub/Sub

Expand Down
8 changes: 6 additions & 2 deletions src/client/baseClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,12 @@ export abstract class BaseClient {
this.queue.forEach(elem => {
this.socket.write(elem);
});
this.handleConnect?.();
});
this.socket.on('data', (data) => {
this.parser.decodeReply(data);
});
this.socket.on('error', (err) => { this.handleError(err); });
this.socket.on('error', err => { this.handleError(err); });
this.socket.on('close', (hadError) => {
/**
* In addition to actively disconnecting the client or server,
Expand All @@ -65,6 +66,7 @@ export abstract class BaseClient {
}, 100);
}

private handleConnect?: () => void;
private handleError(err: Error): void {
console.error(err + '');
}
Expand Down Expand Up @@ -102,14 +104,16 @@ export abstract class BaseClient {
});
}

public on(event: 'message' | 'error', listener: (data: unknown) => void): void {
public on(event: 'message' | 'error' | 'connect', listener: (data?: unknown) => void): void {
switch (event) {
case 'message':
this.parser.on(event, listener);
break;
case 'error':
this.handleError = listener;
break;
case 'connect':
this.handleConnect = listener;
}
}
}

0 comments on commit 96cf2b0

Please sign in to comment.