# SolidJS에서 시그널로 실시간 업데이트

> SolidJS에서 pusher-js로 Hibira 채널을 구독하고, 이벤트를 시그널로 바꾸는 작은 프리미티브를 사용합니다. 소유자와 함께 정리됩니다. 비공개 채널은 SolidStart가 서버에서 서명합니다.

Source: https://hibira.io/ko/guides/solidjs

SolidJS에서 pusher-js로 Hibira 채널을 구독하고, 이벤트를 시그널로 바꾸는 작은 프리미티브를 사용합니다. 소유자와 함께 정리됩니다. 비공개 채널은 SolidStart가 서버에서 서명합니다.

Package: pusher-js

- createEvent는 최신 이벤트를 담은 시그널을 반환하고, 컴포넌트가 언마운트되면 구독을 해제합니다.
- SolidStart API 라우트가 pusher npm 패키지로 비공개·presence 채널에 서명합니다.

## 1. 설치

```shell
npm install pusher-js pusher
```

## 2. 사용하기

```tsx
import Pusher from 'pusher-js';
import { createSignal, onCleanup } from 'solid-js';

const pusher = new Pusher(import.meta.env.VITE_HIBIRA_APP_KEY, {
  cluster: 'hkg',
  wsHost: 'ws.hibira.io',
  channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
});

export function createEvent<T>(channelName: string, event: string) {
  const [value, setValue] = createSignal<T>();
  const channel = pusher.subscribe(channelName);
  const handler = (data: T) => setValue(() => data);
  channel.bind(event, handler);
  onCleanup(() => channel.unbind(event, handler));
  return value;
}

// const order = createEvent<{ id: number }>('orders', 'order.shipped');
```

## 3. 채널 구독에 서명하기

```ts
// src/routes/api/hibira/auth.ts (SolidStart)
import Pusher from 'pusher';

const pusher = new Pusher({
  appId: process.env.HIBIRA_APP_ID!, key: process.env.HIBIRA_APP_KEY!, secret: process.env.HIBIRA_APP_SECRET!,
  host: 'ws.hibira.io', port: '443', useTLS: true,
});

export async function POST({ request }: { request: Request }) {
  const form = await request.formData();
  // check the signed-in user may join this channel first
  return Response.json(pusher.authorizeChannel(String(form.get('socket_id')), String(form.get('channel_name'))));
}
```

## 시작하기 전에

- Free 요금제에서는 페이지를 불러오는 모든 오리진을 앱의 허용 오리진에 등록하세요(개발 중에는 http://localhost:3000, 이후에는 내 도메인). "*"는 유료 요금제에서 쓸 수 있습니다.
- 앱 시크릿은 앱을 만들거나 시크릿을 교체할 때 한 번만 표시됩니다. 서버에만 두고, 브라우저나 게임 빌드에는 절대 넣지 마세요.

- [npm](https://www.npmjs.com/package/pusher-js)
- [npm](https://www.npmjs.com/package/pusher)
