RoomDefinition: onLeave() hook

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The onLeave() hook of a room definition runs when a connection closes, a dropped network included, and for each open connection before the room hibernates.

Syntax

defineRoom({
  onLeave(room, connection, info) {},
});

Parameters

room
The Room.
connection
The Connection that closed.
info

An object with this property:

left
true only when the player’s client closed with client.close().

Return value

None, or a Promise, which the room doesn’t wait for.

Exceptions

If onLeave throws, or its promise rejects, the error is logged. The room keeps running.

Description

onLeave runs:

  • when a connection closes, whether the client closed it, its network dropped, or the room kicked or banned it;
  • for the older connection, with close code 4012, when the same player connects again, before onJoin for the new one;
  • for each open connection before the room hibernates, but not when it goes to sleep;
  • after a sleeping room wakes, for each connection it saved that didn’t come back.

It never runs after a room host crash. A connection closing isn’t the player leaving: the player’s presence lasts 10 seconds more, in case it reconnects. To clean up after a player, use onPlayerLeave(), which a dropped network and a quick reconnect don’t trigger.

left is false for a dropped network, a closed tab or reload, a kick or ban, any close by the router, every onLeave before a hibernation or after a wake, and a connection that closed while its room slept. A client decides when it leaves, so a player about to lose can leave just before; where that matters, ignore left or penalise it. See Quit or dropped.

The connection’s owner writes that came before it closed are applied first, through writes.

Examples

Pausing for a dropped player

// pause.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";

const Match = entity("match", { paused: "bool", waitingFor: "string" });

export default defineRoom({
  schema: defineSchema({ state: Match }),
  onLeave(room, connection, { left }) {
    if (left) return;
    room.state.paused = true;
    room.state.waitingFor = connection.player;
  },
  onJoin(room, connection) {
    if (room.state.waitingFor === connection.player) {
      room.state.paused = false;
      room.state.waitingFor = "";
    }
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
onLeave()0.10.10.10.1