# 從 Hanami 發送即時事件

> 把 pusher gem 註冊為 Hanami 2 provider，從 action 與 operation 發送 Hibira 事件，並在 action 中簽署頻道訂閱。

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

把 pusher gem 註冊為 Hanami 2 provider，從 action 與 operation 發送 Hibira 事件，並在 action 中簽署頻道訂閱。

Package: pusher

- provider 註冊一個 client，action 與 operation 透過 Deps 取得。
- 由 action 為 pusher-js 與 Laravel Echo 簽署私有與 presence 頻道。

## 1. 安裝

```shell
bundle add pusher
```

## 2. 設定

```ruby
# config/providers/hibira.rb
Hanami.app.register_provider(:hibira) do
  prepare { require "pusher" }
  start do
    register "hibira", Pusher::Client.new(
      app_id: target["settings"].hibira_app_id, key: target["settings"].hibira_app_key,
      secret: target["settings"].hibira_app_secret, host: "ws.hibira.io", port: 443, use_tls: true
    )
  end
end

# config/settings.rb: setting :hibira_app_id, setting :hibira_app_key, setting :hibira_app_secret
```

## 3. 使用

```ruby
# app/actions/pusher/auth.rb (config/routes.rb: post "/pusher/auth", to: "pusher.auth")
module Bookshelf
  module Actions
    module Pusher
      class Auth < Bookshelf::Action
        include Deps["hibira"]

        def handle(request, response)
          # check the signed-in user may join request.params[:channel_name] first
          response.format = :json
          response.body = hibira.authenticate(request.params[:channel_name], request.params[:socket_id]).to_json
        end
      end
    end
  end
end

# anywhere: hibira.trigger("orders", "order.shipped", { id: 1042 })
```

## 開始之前

- 應用程式的密鑰只會在建立應用程式或輪替密鑰時顯示一次。請只放在伺服器上，不要放進瀏覽器或遊戲的建置檔。
- Free 方案需要把頁面載入的每個來源都加進應用程式的「允許的來源」（開發時是 http://localhost:3000，之後是您的網域）。"*" 需要付費方案。

- [RubyGems](https://rubygems.org/gems/pusher)
