Skip to content

Commit 9bc8667

Browse files
committed
✨ Socket.IOのwrapperを追加
1 parent d4adcd7 commit 9bc8667

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

browser/websocket/socket.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { Socket, socketIO } from "../../deps/socket.ts";
2+
export type { Socket } from "../../deps/socket.ts";
3+
4+
/** 新しいsocketを作る */
5+
export function makeSocket() {
6+
return socketIO();
7+
}
8+
9+
/** websocketに(再)接続する
10+
*
11+
* @param socket 接続したいsocket
12+
*/
13+
export async function connect(socket: Socket): Promise<void> {
14+
if (socket.connected) return;
15+
socket.connect();
16+
17+
return await new Promise<void>((resolve) =>
18+
socket.once("connect", () => resolve())
19+
);
20+
}
21+
22+
/** websocketを切断する
23+
*
24+
* @param socket 切断したいsocket
25+
*/
26+
export async function disconnect(socket: Socket): Promise<void> {
27+
if (socket.disconnected) return;
28+
socket.disconnect();
29+
30+
return await new Promise<void>((resolve) => {
31+
const onDisconnect = (reason: Socket.DisconnectReason) => {
32+
if (reason !== "io client disconnect") return;
33+
resolve();
34+
socket.off("disconnect", onDisconnect);
35+
};
36+
socket.on("disconnect", onDisconnect);
37+
});
38+
}

deps/socket.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export type {
88
Pin,
99
ProjectUpdatesStreamCommit,
1010
ProjectUpdatesStreamEvent,
11+
Socket,
1112
UpdateCommit,
1213
} from "https://raw.githubusercontent.com/takker99/scrapbox-userscript-websocket/0.1.4/mod.ts";
1314
export {

0 commit comments

Comments
 (0)