Sha256: 9a40d5835b6e8065c5d98bc51047d57206acfd55bb4e69cb2a758f4edd4dd16d

Contents?: true

Size: 1.94 KB

Versions: 2

Compression:

Stored size: 1.94 KB

Contents

# frozen_string_literal: true

require "trellodon/api_client"
require "trellodon/config"

module Trellodon
  class APIExecutor
    BOARD_ID_REGEX = /\/b\/([^\/]+)\//
    private_constant :BOARD_ID_REGEX

    def initialize(api_key:, api_token:, scheduler:, formatter:, logger: Config.logger)
      @api_key = api_key
      @api_token = api_token
      @formatter = formatter
      @logger = logger
      @scheduler = scheduler
      check_credentials!

      @api_client = APIClient.new(api_key: @api_key, api_token: @api_token)
    end

    def download(board_pointer)
      extract_board_id(board_pointer)

      startup_time = Time.now
      logger.debug "Fetching board 🚀️️"
      board = scheduler.post do
        api_client.fetch_board(board_id).tap { |_1| formatter.board_added(_1) }
      end.value

      logger.debug "Fetching cards in board with comments and attachments 🐢"
      board.card_ids.map do |card_id|
        scheduler.post do
          api_client.fetch_card(card_id).tap { |_1| formatter.card_added(_1) }
        end
      end.map(&:value)

      formatter.finish
      logger.debug "All Trello API requests finished in #{(Time.now - startup_time).to_i} seconds ⌛"
    end

    private

    attr_reader :api_client, :board_id, :logger, :scheduler, :formatter

    def check_credentials!
      return if @api_key.to_s.size.positive? && @api_token.to_s.size.positive?

      raise ArgumentError, "Missing credentials. Please fill out both api_key, api_token first."
    end

    def extract_board_id(board_pointer)
      @board_id = if URI::DEFAULT_PARSER.make_regexp.match?(board_pointer)
        parse_board_url(board_pointer)
      else
        board_pointer
      end
    end

    def parse_board_url(board_url)
      rel_path = URI.parse(board_url).request_uri
      match_data = rel_path.match(BOARD_ID_REGEX)
      raise ArgumentError, "Wrong trello board url" if match_data.nil? || match_data.size != 2

      match_data[1]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
trellodon-0.2.1 lib/.rbnext/2.7/trellodon/api_executor.rb
trellodon-0.2.0 lib/.rbnext/2.7/trellodon/api_executor.rb