# 在 Qwik 中接收实时更新

> Qwik 组件在可见时才连接到 Hibira，让 pusher-js 不进入首次加载；私有频道在 Qwik City endpoint 中签署。

Source: https://hibira.io/zh-cn/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)
