用于webpush通知的rake任务

时间:2017-04-25 08:43:00

标签: javascript jquery ruby-on-rails ruby service-worker

我有 challenge_reminder.rake

task challenge_reminder: :environment do
  Challenge.unaccomplished.all.each do |challenge|
    if challenge.remind.include? Date::ABBR_DAYNAMES[Date.current.wday].downcase
        if challenge.mail == true # This Works
            UserMailer.challenge_reminder(challenge).deliver_now 
        end
        if challenge.push == true 
          # How to send webpush notification for challenge
        end 
    end      
  end 
end

如果用户手动点击按钮,则用户可以收到推送通知...

<%= content_tag(:button, "Foo", class: "webpush-button") %>

<script>
  $('.webpush-button').on('click', (e) => {
    navigator.serviceWorker.ready
    .then((serviceWorkerRegistration) => {
      serviceWorkerRegistration.pushManager.getSubscription()
      .then((subscription) => {
        console.log('Almost there, Daddy!');
        $.post('/push', {
          subscription: subscription.toJSON(),
          message: 'You clicked a button!'
        });
      });
    });
  });
</script>

导致......

class PushNotificationsController < ApplicationController
  def push
    Webpush.payload_send(
      message: params[:message],
      endpoint: params[:subscription][:endpoint],
      p256dh: params[:subscription][:keys][:p256dh],
      auth: params[:subscription][:keys][:auth],
      vapid: {
        subject: "mailto:sender@example.com",
        public_key: ENV['VAPID_PUBLIC_KEY'],
        private_key: ENV['VAPID_PRIVATE_KEY']
      }
    )
  end
end

如何调整rake任务的脚本代码?

我通过serviceworker gemwebpush gem和VAPID凭据实施了推送。

1 个答案:

答案 0 :(得分:0)

您应该将整个逻辑从PushNotificationsController#push移动到某些域逻辑或者可能是服务 - PushNotificationsService,这可以在差异处使用:

class PushNotificationsService
  def self.call(params) 
    Webpush.payload_send(
      message: params[:message],
      endpoint: params[:subscription][:endpoint],
      p256dh: params[:subscription][:keys][:p256dh],
      auth: params[:subscription][:keys][:auth],
      vapid: {
        subject: "mailto:sender@example.com",
        public_key: ENV['VAPID_PUBLIC_KEY'],
        private_key: ENV['VAPID_PRIVATE_KEY']
      } 
    )
  end
end

然后,您可以从应用中的差异点调用此服务,即。 PushNotificationsService.call(params)

希望这有帮助!