# Qwik에서 실시간 업데이트

> Qwik 컴포넌트가 화면에 보일 때만 Hibira에 연결하므로 pusher-js가 첫 로드에 포함되지 않으며, 비공개 채널은 Qwik City 엔드포인트에서 서명합니다.

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

Qwik 컴포넌트가 화면에 보일 때만 Hibira에 연결하므로 pusher-js가 첫 로드에 포함되지 않으며, 비공개 채널은 Qwik City 엔드포인트에서 서명합니다.

Package: pusher-js

- useVisibleTask$가 필요할 때 pusher-js를 불러오고 cleanup에서 연결을 끊습니다.
- Qwik City onPost 엔드포인트가 pusher npm 패키지로 비공개·presence 채널에 서명합니다.

## 1. 설치

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

## 2. 사용하기

```tsx
import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';

export default component$(() => {
  const status = useSignal('Waiting for updates');
  useVisibleTask$(async ({ cleanup }) => {
    const { default: Pusher } = await import('pusher-js');
    const pusher = new Pusher(import.meta.env.PUBLIC_HIBIRA_APP_KEY, {
      cluster: 'hkg',
      wsHost: 'ws.hibira.io',
      channelAuthorization: { endpoint: '/api/hibira/auth', transport: 'ajax' },
    });
    pusher.subscribe('orders').bind('order.shipped', (o: { id: number }) => (status.value = `Order #${o.id} shipped`));
    cleanup(() => pusher.disconnect());
  });
  return <p>{status.value}</p>;
});
```

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

```ts
// src/routes/api/hibira/auth/index.ts
import type { RequestHandler } from '@builder.io/qwik-city';
import Pusher from 'pusher';

export const onPost: RequestHandler = async ({ parseBody, env, json }) => {
  const pusher = new Pusher({
    appId: env.get('HIBIRA_APP_ID')!, key: env.get('HIBIRA_APP_KEY')!, secret: env.get('HIBIRA_APP_SECRET')!,
    host: 'ws.hibira.io', port: '443', useTLS: true,
  });
  const form = (await parseBody()) as Record<string, string>;
  // check the signed-in user may join this channel first
  json(200, pusher.authorizeChannel(form.socket_id, form.channel_name));
};
```

## 시작하기 전에

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

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