# Hanami에서 실시간 이벤트

> pusher gem을 Hanami 2 provider로 등록하고, action과 operation에서 Hibira 이벤트를 보내고, action에서 채널 구독에 서명합니다.

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

pusher gem을 Hanami 2 provider로 등록하고, action과 operation에서 Hibira 이벤트를 보내고, action에서 채널 구독에 서명합니다.

Package: pusher

- provider가 클라이언트 하나를 등록하고, 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)
