> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sunra.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript / TypeScript

[![@sunra/client npm 패키지](https://img.shields.io/npm/v/@sunra/client?color=%237527D7\&label=JavaScript\&style=flat-square)](https://www.npmjs.com/package/@sunra/client)

### 소개

JavaScript/TypeScript용 클라이언트 라이브러리는 Sunra의 서비스와 상호 작용하기 쉬운 인터페이스를 제공합니다.

### 설치

프로젝트에 클라이언트를 통합하려면 npm을 사용하여 설치하십시오.

<CodeGroup>
  ```bash npm theme={null}
  npm install @sunra/client
  ```

  ```bash pnpm theme={null}
  pnpm add @sunra/client
  ```

  ```bash yarn theme={null}
  yarn add @sunra/client
  ```
</CodeGroup>

### 기능

#### 엔드포인트 호출

Sunra는 대기열 시스템을 통해 엔드포인트 요청을 관리하여 안정성과 확장성을 보장합니다. `subscribe` 메서드를 사용하여 요청을 제출하고 결과를 기다립니다.

**예시:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const result = await sunra.subscribe("black-forest-labs/flux-kontext-pro/text-to-image", {
  input: {
    prompt: "햇살이 비치는 창가 나무 테이블 위에 놓인, 꽃차가 피어나는 유리 찻주전자.",
    "aspect_ratio": "16:9",
    "output_format": "jpeg",
  },
  logs: true,
  onQueueUpdate: (update) => {
    if (update.status === "IN_PROGRESS") {
      console.log(update.logs)
    }
  },
});

console.log(result.data);
console.log(result.requestId);
```

#### 대기열 관리

다음 메서드로 요청을 관리합니다.

##### 요청 제출

요청을 제출하고 나중에 사용할 `request_id`를 검색합니다.

**예시:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const { request_id } = await sunra.queue.submit("black-forest-labs/flux-kontext-max", {
  input: {
    prompt: "햇살이 비치는 창가 나무 테이블 위에 놓인, 꽃차가 피어나는 유리 찻주전자.",
    "aspect_ratio": "16:9",
    "output_format": "jpeg",
  },
});
```

##### 요청 상태 확인

요청 상태를 검색합니다.

**예시:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const status = await sunra.queue.status({
  requestId: "pd_eTYYuw4EqYLzRBHgnAMHA8zH",
  logs: true,
});
```

##### 요청 결과 검색

완료된 요청의 결과를 가져옵니다.

**예시:**

```javascript theme={null}
import { sunra } from "@sunra/client";

const result = await sunra.queue.result({
  requestId: "pd_eTYYuw4EqYLzRBHgnAMHA8zH",
});

console.log(result.data);
console.log(result.requestId);
```

#### 저장소

`storage` API를 사용하면 파일을 업로드하고 URL을 받을 수 있으며, 이 URL은 모델 엔드포인트 요청에 사용할 수 있습니다. 이는 이미지-비디오 또는 음성-텍스트와 같이 파일 입력이 필요한 모델에 특히 유용합니다.

<Note>최대 파일 크기: 100MB</Note>

##### 브라우저에서 파일 업로드

사용자가 브라우저에서 직접 파일을 업로드하도록 허용할 수 있습니다. 다음 예제는 `<input type="file">` 요소를 사용하여 파일을 선택하고 업로드하는 방법을 보여줍니다.

<CodeGroup>
  ```javascript upload.js theme={null}
  import { sunra } from "@sunra/client";

  const fileInput = document.getElementById('file-input');

  fileInput.addEventListener('change', async (event) => {
    const file = event.target.files[0];
    if (file) {
      try {
        const url = await sunra.storage.upload(file);
        console.log('파일이 성공적으로 업로드되었습니다:', url);
        // 이제 이 URL을 모델 엔드포인트와 함께 사용할 수 있습니다.
      } catch (error) {
        console.error('업로드 실패:', error);
      }
    }
  });
  ```

  ```html index.html theme={null}
  <input type="file" id="file-input" />
  ```
</CodeGroup>

##### Node.js에서 파일 업로드

Node.js를 사용하는 서버 측에서는 로컬 파일 시스템에서 파일을 읽고 업로드할 수 있습니다.

```javascript theme={null}
import { sunra } from "@sunra/client";
import { readFile } from "node:fs/promises";
import { basename } from "node:path";

async function uploadLocalFile(filePath) {
  try {
    const buffer = await readFile(filePath);
    // 클라이언트는 버퍼에서 생성할 수 있는 File 객체가 필요합니다.
    const file = new File([buffer], basename(filePath));

    const url = await sunra.storage.upload(file);
    console.log('파일이 성공적으로 업로드되었습니다:', url);
    return url;
  } catch (error) {
    console.error('업로드 실패:', error);
  }
}

uploadLocalFile("./path/to/your/image.png");
```

#### 모델 엔드포인트를 사용한 자동 업로드

JavaScript SDK는 파일 업로드를 자동으로 처리할 수 있습니다. `File` 객체, `Blob` 또는 base64 데이터 URI를 모델 엔드포인트의 입력으로 전달하면 SDK는 먼저 이를 스토리지에 업로드한 다음 요청에서 결과 URL을 사용합니다.

이렇게 하면 별도의 업로드 단계를 수행할 필요가 없으므로 프로세스가 단순화됩니다.

```javascript theme={null}
import { sunra } from "@sunra/client";

// 브라우저 파일 입력의 File 객체는 자동으로 업로드됩니다.
const fileInput = document.getElementById('file-input');
const file = fileInput.files[0];

const result = await sunra.subscribe("some-model-that-takes-images", {
  input: {
    image: file, // SDK가 이 파일을 자동으로 업로드합니다.
    prompt: "이미지로 무엇을 할지 설명하는 프롬프트"
  }
});

// base64 데이터 URI도 자동으로 업로드됩니다.
const base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...";

const result2 = await sunra.subscribe("some-model-that-takes-images", {
  input: {
    image: base64Image, // SDK가 이를 Blob으로 자동 변환하여 업로드합니다.
    prompt: "이미지로 무엇을 할지 설명하는 프롬프트"
  }
});
```

### 지원

도움이나 토론을 위해 커뮤니티에 가입하십시오.

* **Discord 커뮤니티**: [가입하기](https://discord.gg/897qCzvCcU)
* **GitHub 리포지토리**: [방문하기](https://github.com/sunra-ai/sunra-clients)

저희가 도와드리겠습니다!
