closeClient
The closeClient method is used to close a client's WebSocket.
closeClient(
clientId: string,
code?: number,
reason?: string,
): void| Type | Description | |
|---|---|---|
clientId | string | The |
code? | number | An optional WebSocket close code: either |
reason? | string | An optional reason, of up to 123 bytes, that the client can read. |
| returns | void | This has no return value. |
The authorize method is only called when a client joins the path. So if the client is later no longer allowed to be there, because its user has logged out, for example, use this method to close it. From then on, nothing that the client sends is used, even if it never answers, and it is sent nothing more. But until it does answer, or its connection is lost, the getClientIds method still returns its Id.
The client may try to connect again, as a ReconnectingWebSocket does. So before closing it, make sure that the authorize method would now refuse it.
This method does nothing if there is no such client, or if it is already being closed.
Example
This example adds a method to a Durable Object that a Worker can call when a user logs out, which closes each of that user's clients. The user's token must already have been revoked, so that they cannot join again.
import {WsServerDurableObject} from 'tinybase/synchronizers/synchronizer-ws-server-durable-object';
export class MyDurableObject extends WsServerDurableObject {
async authorize(pathId, request) {
const user = await this.env.TOKENS.get(
new URL(request.url).searchParams.get('token'),
);
return user ? {context: {user}} : undefined;
}
closeUser(user) {
this.getClientIds().forEach((clientId) => {
if (this.getClientAccess(clientId)?.context.user == user) {
this.closeClient(clientId, 4001, 'Logged out');
}
});
}
}
Since
v10.2.0