官方包 · 框架

在 Qwik 中接收实时更新

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

最快的方式:装好 Hibira 插件,粘贴一段提示词

在你的 AI 编程助手装好插件,再粘贴提示词。助手会帮你登录、需要时创建免费应用、写好代码并发送测试事件。 GitHub ↗

  1. 安装插件

    claude plugin marketplace add hibira-io/agent-plugin
    claude plugin install hibira@hibira
  2. 粘贴这段提示词

    Add Hibira Qwik (pusher-js) to this project.
    Follow https://hibira.io/guides/qwik, adapted to how this project is already set up.
    If I have no Hibira app yet, create a Free one that allows http://localhost so I can test right away.
    Keep the app key and secret in environment variables, add placeholders to .env.example, and never commit real values or send the secret to a browser.
    When you are done, send a test event, show me it arriving, and list the files you changed.
  • useVisibleTask$ 按需加载 pusher-js,并在清理时断开连接。
  • Qwik City 的 onPost endpoint 使用 pusher npm 包签署私有和 presence 频道。

登录后,示例代码会自动填入您的集群主机。 登录

  1. 安装

    npm install pusher-js pusher
  2. 使用

    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. 签署频道订阅

    // 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,之后是您的域名)。"*" 需要付费套餐。
  • 应用密钥只会在创建应用或轮换密钥时显示一次。请只放在服务器上,不要放进浏览器或游戏的构建包。

请使用控制台中应用的 Key;Secret 只放在你的服务器上。频道、事件与授权端点的用法与 Pusher 完全相同。 免费创建账号 →