Sha256: 654867d75399ace23e6b0a38d0bdcd34f6b4e7a1776f9277d836826908aa9dbb

Contents?: true

Size: 1.47 KB

Versions: 6

Compression:

Stored size: 1.47 KB

Contents

module SpiffyStoresApp
  class WebhooksManager
    class CreationFailed < StandardError; end

    def self.queue(shop_domain, shop_token, webhooks)
      SpiffyStoresApp::WebhooksManagerJob.perform_later(
        shop_domain: shop_domain,
        shop_token: shop_token,
        webhooks: webhooks
      )
    end

    attr_reader :required_webhooks

    def initialize(webhooks)
      @required_webhooks = webhooks
    end

    def recreate_webhooks!
      destroy_webhooks
      create_webhooks
    end

    def create_webhooks
      return unless required_webhooks.present?

      required_webhooks.each do |webhook|
        create_webhook(webhook) unless webhook_exists?(webhook[:topic])
      end
    end

    def destroy_webhooks
      SpiffyStoresAPI::Webhook.all.to_a.each do |webhook|
        SpiffyStoresAPI::Webhook.delete(webhook.id) if is_required_webhook?(webhook)
      end

      @current_webhooks = nil
    end

    private

    def is_required_webhook?(webhook)
      required_webhooks.map{ |w| w[:address] }.include? webhook.address
    end

    def create_webhook(attributes)
      attributes.reverse_merge!(format: 'json')
      webhook = SpiffyStoresAPI::Webhook.create(attributes)
      raise CreationFailed, webhook.errors.full_messages.to_sentence unless webhook.persisted?
      webhook
    end

    def webhook_exists?(topic)
      current_webhooks[topic]
    end

    def current_webhooks
      @current_webhooks ||= SpiffyStoresAPI::Webhook.all.index_by(&:topic)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
spiffy_stores_app-8.2.11 lib/spiffy_stores_app/managers/webhooks_manager.rb
spiffy_stores_app-8.2.10 lib/spiffy_stores_app/managers/webhooks_manager.rb
spiffy_stores_app-8.2.9 lib/spiffy_stores_app/managers/webhooks_manager.rb
spiffy_stores_app-8.2.8 lib/spiffy_stores_app/managers/webhooks_manager.rb
spiffy_stores_app-8.2.7 lib/spiffy_stores_app/managers/webhooks_manager.rb
spiffy_stores_app-8.2.6 lib/spiffy_stores_app/managers/webhooks_manager.rb