# Sự kiện thời gian thực từ Hanami

> Đăng ký gem pusher làm provider của Hanami 2, gửi sự kiện Hibira từ action và operation, và ký đăng ký kênh trong một action.

Source: https://hibira.io/vi/guides/hanami

Đăng ký gem pusher làm provider của Hanami 2, gửi sự kiện Hibira từ action và operation, và ký đăng ký kênh trong một action.

Package: pusher

- Một provider đăng ký một client; action và operation lấy nó qua Deps.
- Một action ký kênh riêng tư và presence cho pusher-js và Laravel Echo.

## 1. Cài đặt

```shell
bundle add pusher
```

## 2. Thiết lập

```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. Sử dụng

```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 })
```

## Trước khi bắt đầu

- Secret của ứng dụng chỉ hiện một lần, khi bạn tạo ứng dụng hoặc xoay vòng secret. Hãy giữ nó trên máy chủ, không bao giờ đưa vào trình duyệt hay bản build game.
- Với gói Free, hãy thêm mọi origin mà trang của bạn tải từ đó vào Origin được phép của ứng dụng (http://localhost:3000 khi phát triển, sau đó là tên miền của bạn). "*" cần gói trả phí.

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