Skip to content

Commit fba7f5f

Browse files
committed
✨ Enable to run listenStream() with an existing socket
1 parent 9056916 commit fba7f5f

File tree

2 files changed

+53
-35
lines changed

2 files changed

+53
-35
lines changed

browser/websocket/listen.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import {
2+
ProjectUpdatesStreamCommit,
3+
ProjectUpdatesStreamEvent,
4+
Socket,
5+
socketIO,
6+
wrap,
7+
} from "../../deps/socket.ts";
8+
import { connect, disconnect } from "./socket.ts";
9+
import { getProjectId } from "./id.ts";
10+
export type {
11+
ProjectUpdatesStreamCommit,
12+
ProjectUpdatesStreamEvent,
13+
} from "../../deps/socket.ts";
14+
15+
export interface ListenStreamOptions {
16+
socket?: Socket;
17+
}
18+
19+
/** Streamを購読する
20+
*
21+
* @param project 購読したいproject
22+
* @param events 購読したいevent。配列で指定する
23+
* @param options 使用したいSocketがあれば指定する
24+
*/
25+
export async function* listenStream(
26+
project: string,
27+
events: ["commit" | "event", ...("commit" | "event")[]],
28+
options?: ListenStreamOptions,
29+
): AsyncGenerator<
30+
ProjectUpdatesStreamEvent | ProjectUpdatesStreamCommit,
31+
void,
32+
unknown
33+
> {
34+
const projectId = await getProjectId(project);
35+
36+
const injectedSocket = options?.socket;
37+
const socket = injectedSocket ?? await socketIO();
38+
await connect(socket);
39+
const { request, response } = wrap(socket);
40+
41+
// 部屋に入って購読し始める
42+
await request("socket.io-request", {
43+
method: "room:join",
44+
data: { projectId, pageId: null, projectUpdatesStream: true },
45+
});
46+
try {
47+
yield* response(
48+
...events.map((event) => `projectUpdatesStream:${event}` as const),
49+
);
50+
} finally {
51+
if (!injectedSocket) await disconnect(socket);
52+
}
53+
}

browser/websocket/stream.ts

Lines changed: 0 additions & 35 deletions
This file was deleted.

0 commit comments

Comments
 (0)