Skip to content

Commit ada34da

Browse files
committed
fix: ultra clean ws
1 parent a44f34f commit ada34da

File tree

2 files changed

+28
-11
lines changed

2 files changed

+28
-11
lines changed

apps/backend/src/http/routes/ws.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,19 @@ export const wsRoutes = async (app: App) => {
1414
})
1515
}
1616
},
17-
(conn, req) => {
17+
async (conn, req) => {
18+
const disconnect = await app.pubsub.subscribe(
19+
req.params.roomCode,
20+
message => {
21+
conn.socket.send(JSON.stringify(message));
22+
}
23+
);
24+
1825
conn.socket.on('ping', () => {
1926
conn.socket.pong();
2027
});
2128

22-
app.pubsub.subscribe(req.params.roomCode, message => {
23-
console.log('message', message);
24-
conn.socket.send(JSON.stringify(message));
25-
});
29+
conn.socket.on('close', disconnect);
2630
}
2731
);
2832

@@ -38,14 +42,19 @@ export const wsRoutes = async (app: App) => {
3842
})
3943
}
4044
},
41-
(conn, req) => {
45+
async (conn, req) => {
46+
const disconnect = await app.pubsub.subscribe(
47+
req.params.userId,
48+
message => {
49+
conn.socket.send(JSON.stringify(message));
50+
}
51+
);
52+
4253
conn.socket.on('ping', () => {
4354
conn.socket.pong();
4455
});
4556

46-
app.pubsub.subscribe(req.params.userId, message => {
47-
conn.socket.send(JSON.stringify(message));
48-
});
57+
conn.socket.on('close', disconnect);
4958
}
5059
);
5160
};

apps/backend/src/lib/pub-sub.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,21 @@ export class Pubsub {
1414
await this.redis.publish(channel, JSON.stringify(event));
1515
}
1616

17-
public async subscribe(channel: string, cb: (event: Event) => void) {
17+
public async subscribe(
18+
channel: string,
19+
cb: (event: Event) => void
20+
): Promise<() => Promise<void>> {
1821
const sub = this.redis.duplicate();
1922

20-
sub.on('room.message', (_, message) => {
23+
sub.on('message', (_, message) => {
2124
cb(JSON.parse(message));
2225
});
2326

2427
await sub.subscribe(channel);
28+
29+
return async () => {
30+
await sub.unsubscribe(channel);
31+
sub.quit();
32+
};
2533
}
2634
}

0 commit comments

Comments
 (0)