Skip to content

Commit

Permalink
detect socket close and send phx_leave to component manager
Browse files Browse the repository at this point in the history
  • Loading branch information
floodfx committed Mar 7, 2022
1 parent 22b1cab commit 02cfecb
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/server/live_view_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,12 @@ export class LiveViewServer {
const connectionId = nanoid();
// handle ws messages
socket.on('message', async message => {
console.log("received message", connectionId);
await this.messageRouter.onMessage(socket, message, this._router, connectionId, this.signingSecret);
});
socket.on('close', async code => {
await this.messageRouter.onClose(code, connectionId);
})
});

this.httpServer.listen(this.port, () => {
Expand Down
10 changes: 7 additions & 3 deletions src/server/socket/message_router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@ export type PhxMessage =

export class MessageRouter {

async onMessage(ws: WebSocket, message: WebSocket.RawData, router: LiveViewRouter, connectionId: string, signingSecret: string) {
public async onMessage(ws: WebSocket, message: WebSocket.RawData, router: LiveViewRouter, connectionId: string, signingSecret: string) {
// parse string to JSON
const rawPhxMessage: PhxIncomingMessage<unknown> = JSON.parse(message.toString());

// rawPhxMessage must be an array with 5 elements
if (typeof rawPhxMessage === 'object' && Array.isArray(rawPhxMessage) && rawPhxMessage.length === 5) {
const [joinRef, messageRef, topic, event, payload] = rawPhxMessage;

let componentManager: LiveViewComponentManager | undefined;
try {
switch (event) {
case "phx_join":
Expand Down Expand Up @@ -54,8 +53,13 @@ export class MessageRouter {

}

public async onClose(code: number, connectionId: string) {
// when client closes connection send phx_leave message
// to component manager via connectionId broadcast
await PubSub.broadcast(connectionId, {type: "phx_leave", message: [null, null, "phoenix", "phx_leave", {}]});
}

async onPhxJoin(ws: WebSocket, message: PhxJoinIncoming, router: LiveViewRouter, signingSecret: string, connectionId: string) {
private async onPhxJoin(ws: WebSocket, message: PhxJoinIncoming, router: LiveViewRouter, signingSecret: string, connectionId: string) {
// use url to route join request to component
const [joinRef, messageRef, topic, event, payload] = message;
const { url: urlString, redirect: redirectString } = payload;
Expand Down

0 comments on commit 02cfecb

Please sign in to comment.