# 在 Qwik 接收即時更新

> Qwik 元件在可見時才連線到 Hibira，讓 pusher-js 不進入首次載入；私有頻道在 Qwik City endpoint 簽署。

Source: https://hibira.io/zh-tw/guides/qwik

Qwik 元件在可見時才連線到 Hibira，讓 pusher-js 不進入首次載入；私有頻道在 Qwik City endpoint 簽署。

Package: pusher-js

- useVisibleTask$ 按需載入 pusher-js，並在清除時中斷連線。
- Qwik City 的 onPost endpoint 以 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)
