# Server Class

## Content

[Server](/spreadjs/api/collaboration/js-collaboration/classes/Server) 클래스는 `js-collaboration`의 핵심 구성 요소로, 클라이언트 연결과 메시지 흐름을 관리합니다. 이 문서에서는 해당 클래스의 기능과 사용 방법을 소개합니다.

## 개요

`Server` 클래스 자체에는 비즈니스 로직이 포함되어 있지 않습니다. 이 클래스는 클라이언트 연결, 메시지, 연결 해제 이벤트를 수신하고, **훅(hooks)** 및 **미들웨어(middleware)** 메커니즘을 통해 개발자가 처리할 수 있도록 위임하는 역할만 수행합니다.

* **미들웨어(Middleware)**: 인증, 권한 검증과 같이 연결 또는 메시지 흐름을 가로채(intercept) 처리하는 데 사용됩니다.
* **훅(Hooks)**: 연결 수립이나 메시지 수신과 같은 이벤트를 감지(listen)하여, 워크플로에 영향을 주지 않고 사용자 정의 로직을 실행하는 데 사용됩니다.

개발자는 미들웨어와 훅을 등록하여 비즈니스 로직을 구현하며, 서버는 오직 이벤트 디스패처 역할만 수행합니다.

## 라이프사이클

![server_class-lifecycle.30782d.png](https://gcdocumentsitekrblob.blob.core.windows.net/document-site-files/images/36b63360-fb01-457c-a448-c3ce32aaf454/server_class-lifecycle.30782d-20260106.e1b2a1.png)

## 초기화

[Server 초기화](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration/initalizing-server)

## 메서드

### 훅 등록 (`on`)

연결, 메시지, 연결 해제와 같은 서버 라이프사이클 이벤트를 수신합니다.
**일괄 등록(Batch Registration)**:

```typescript
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)**:

```typescript
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
> 훅은 워크플로를 가로채지 않으며, 부가적인 로직을 실행하는 용도로만 사용됩니다.

### 미들웨어 등록 (`use`)

이벤트 처리 전에 인증이나 로깅과 같은 가로채기(interception) 로직을 실행합니다.

```typescript
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);
    }
});
```

미들웨어에 대한 자세한 내용은 다음을 참고하세요:
[Server Middleware](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration/server-middleware)

### 기능 등록 (`useFeature`)

`useFeature` 메서드는 미들웨어와 훅을 동시에 등록할 수 있게 해줍니다. OT(Operational Transformation)나 Presence(사용자 온라인 상태)와 같은 확장 기능은 기능(feature) 형태로 제공됩니다.

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

server.useFeature(documentFeature());
```

#### 인터페이스

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

## 기본 사용 사례

1. 미들웨어를 사용한 인증 및 권한 검증
    참고: [사용자 인증 및 권한](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration/user-authentication-and-permissions)
2. 훅을 사용한 이벤트 처리

```typescript
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}`);
    }
});
```

## 다음 단계

* 클라이언트로 메시지 전송/브로드캐스트: [Server Connection Class](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration/server-connection-class)
* 미들웨어 메커니즘에 대한 상세 설명: [Server Middleware](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration/server-middleware)
* 다중 서버 배포 시: [Multiple Servers Deployment](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration/multiple-servers-deployment)