# DocumentServices 초기화

## Content

이 문서는 서버 측에서 [DocumentServices](/spreadjs/api/collaboration/js-collaboration-ot/classes/DocumentServices)를 초기화하는 방법을 설명하며, 다음 내용을 포함합니다.

* 의존성 설치
* 서버 인스턴스 생성
* OT 기능 구성

## 설치

npm을 통해 필요한 의존성 패키지를 설치합니다.

```bash
npm install @mescius/js-collaboration @mescius/js-collaboration-ot
```

* `js-collaboration`: 기본 서버 기능과 [Server](/spreadjs/api/collaboration/js-collaboration/classes/Server) 클래스를 제공합니다.
* `js-collaboration-ot`: [documentFeature](/spreadjs/api/collaboration/js-collaboration-ot/README#documentfeature) 및 OT 타입 관리를 포함한 OT 기능을 제공합니다.

## 서버 초기화

1. OT 타입 등록
    서버를 시작하기 전에 작업 동작을 정의하기 위해 [OT_Types](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration-ot/ottypes)을 등록해야 합니다. 다음은 간단한 텍스트 타입을 등록하는 예제입니다.

    ```typescript
    import { TypesManager } from '@mescius/js-collaboration-ot';
    
    const textType = {
        uri: 'rich-text-ot-type'
        create: (data) => data || '',
        transform: (op1, op2, side) => {
            if (op1.pos < op2.pos) return op1;
            return { pos: op1.pos + op2.text.length, text: op1.text };
        },
        apply: (snapshot, op) => {
            return snapshot.slice(0, op.pos) + op.text + snapshot.slice(op.pos);
        }
    };
    
    TypesManager.register(textType);
    ```
2. 서버 인스턴스 생성
    `js-collaboration`의 [Server](/spreadjs/api/collaboration/js-collaboration/classes/Server) 클래스를 사용하여 서버 인스턴스를 생성합니다.

    ```typescript
    import { Server } from '@mescius/js-collaboration';
    
    const server = new Server({ port: 8080 });
    ```

    **역할**: 서버를 초기화하고 WebSocket 연결을 수신합니다.
3. OT 기능 통합
    `js-collaboration-ot`의 [documentFeature](/spreadjs/api/collaboration/js-collaboration-ot/README#documentfeature)를 사용하여 서버에 OT 기능을 추가합니다.

    ```typescript
    import { documentFeature } from '@mescius/js-collaboration-ot';
    
    // OT 기능 통합
    server.useFeature(documentFeature());
    ```

    **매개변수**
    `service` (선택 사항): 사용자 지정 데이터베이스 및 구성을 위한 `DocumentServices` 인스턴스(고급 구성 참조).
<br>
    **역할**: OT 문서 기능을 활성화하여 서버가 작업과 스냅샷을 처리할 수 있도록 합니다.

## 전체 예제

다음은 서버 초기화의 전체 예제입니다.

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

// OT 타입 정의
const textType = {
    uri: 'text',
    create: (data) => data || '',
    transform: (op1, op2, side) => {
        if (op1.pos < op2.pos) return op1;
        return { pos: op1.pos + op2.text.length, text: op1.text };
    },
    apply: (snapshot, op) => {
        return snapshot.slice(0, op.pos) + op.text + snapshot.slice(op.pos);
    }
};
// OT 타입 등록
TypesManager.register(textType);

// 서버 생성
const server = new Server({ port: 8080 });

// OT 기능 통합
server.useFeature(documentFeature());

// 선택 사항: 연결 이벤트 수신
server.on('connect', ({ connection }) => {
    console.log(`클라이언트 ${connection.id}가 연결되었습니다`);
});
```

## 고급 구성

OT 동작이나 데이터 저장 방식을 사용자 지정해야 하는 경우, `DocumentServices`를 구성한 후 `documentFeature`에 전달할 수 있습니다.

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

// DocumentServices 구성
const docService = new DocumentServices({
    db: new MemoryDb(), // 인메모리 데이터베이스 사용
    submitSnapshotBatchSize: 50 // 스냅샷 제출 배치 크기
});

// OT 기능 통합
server.useFeature(documentFeature(docService));
```

**매개변수** (`IDocConfig`):

* `db`: 데이터베이스 어댑터(기본값은 `MemoryDb`)
* `maxSubmitRetries`: 작업 제출의 최대 재시도 횟수(기본값: 무제한)
* `submitSnapshotBatchSize`: 스냅샷 제출 배치 크기(기본값: 100)

## 다음 단계

[DocumentServices 구성 및 사용](/spreadjs/docs/spreadjs-collaboration-server/collaboration-framework/js-collaboration-ot/constructing-and-using-documentservices)