[]
        
(Showing Draft Content)

Server Class

The Server class constitutes the core of js-collaboration, managing client connections and message workflows. This document introduces its functionality and usage.

Summary

The Server class itself does not contain any business logic. It is only responsible for receiving client connections, messages, and disconnection events, and delegating these events to developers for handling through hooks and middleware mechanisms.

  • Middleware: Used to intercept and process connection or message workflows, such as authentication or permission validation.

  • Hooks: Used to listen for events (e.g., connection establishment or message reception) and execute custom logic without affecting the workflow.

Developers implement business logic by registering middleware and hooks, while the server acts solely as an event dispatcher.

Lifecycle

server_class-lifecycle

Initialization

Initalizing Server

Methods

Register Hook (on)

Listen for server lifecycle events, such as connection, message, or disconnection.

Batch Registration:

server.on({
    connect: ({ connection }) => {
        console.log(`${connection.id} connected`);
    },
    message: ({ data, type }) => {
        console.log(`Received message: ${data} (type: ${type})`);
    },
    disconnect: ({ connection }) => {
        console.log(`${connection.id} disconnected`);
    }
});

Individual Registration:

server.on('connect', ({ connection }) => {
    console.log(`${connection.id} connected`);
});
server.on('message', ({ data, type }) => {
    console.log(`Received message: ${data} (type: ${type})`);
});
server.on('disconnect', ({ connection }) => {
    console.log(`${connection.id} disconnected`);
});

type=note

Hooks do not intercept the workflow; they are only used for additional logic.

Register Middleware (use)

Execute interception logic before event handling, such as authentication or logging.

server.use({
    connect: async (context, next) => {
        if (context.connection.auth.token === 'valid-token') {
            await next();
        } else {
            await next('Authentication failed');
        }
    },
    message: async ({ data }, next) => {
        console.log('message:', data);
    }
});

For more information on middleware, refer to: Server Middleware

Register Feature (useFeature)

The useFeature method allows simultaneous registration of middleware and hooks. Some extended functionalities, such as OT (Operational Transformation) and Presence (user online status), are provided in the form of features.

import { documentFeature } from '@mescius/js-collaboration-ot';

server.useFeature(documentFeature());

Interface

export interface IFeature {
    middlewares?: IMiddlewares;
    hooks?: IHooks;
}

Basic Use Cases

  1. Using Middleware for Authentication and Permission Validation

    Refer to: User Authentication and Permissions

  2. Using Hooks to Handle Events

    server.on({
        enterRoom: ({ connection, roomId }) => {
            console.log(`${connection.id} joined ${roomId}`);
        },
        message: ({ connection, roomId, data }) => {
            console.log(`Received message from ${connection.id}: ${data}`);
            console.log(`Broadcasting message to ${roomId}: ${data}`);
            connection.broadcast(data);
        },
        leaveRoom: ({ connection, roomId }) => {
            console.log(`${connection.id} left ${roomId}`);
        }
    });

Next Steps