Sha256: 382ed26d9ab9f7f182f2b06be0f0b91986be672461d180dfe66322f9cfe9ca3d

Contents?: true

Size: 1.02 KB

Versions: 8

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

module WCC::Blogs
  class Client
    def initialize(config:)
      @config = config
    end

    REDIRECT_HANDLER =
      ->(resp) {
        location = resp.headers['Location']
        digest = File.basename(location).gsub(/\.(fragment|json)$/, '')

        @config.cache.fetch(['BlogPost', digest, File.extname(location)]) do
          get(location, resp.effective_url)
        end
      }

    RESPONSE_HANDLERS = {
      404 => ->(resp) {
        raise WCC::Blogs::NotFoundException, "Blog post '#{resp.effective_url}' does not exist"
      },
      200 => ->(resp) {
        resp.body
      },
      301 => REDIRECT_HANDLER,
      302 => REDIRECT_HANDLER,
    }.freeze

    def get(path, base = @config.base_url)
      url = URI.join(base, path)

      resp = Typhoeus.get(url, followlocation: false)

      if handler = RESPONSE_HANDLERS[resp.code]
        return instance_exec(resp, &handler)
      end

      raise WCC::Blogs::ApiException, "#{resp.return_code}: #{resp.effective_url}"
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
wcc-blogs-client-0.3.4 lib/wcc/blogs/client.rb
wcc-blogs-client-0.3.3 lib/wcc/blogs/client.rb
wcc-blogs-client-0.3.2 lib/wcc/blogs/client.rb
wcc-blogs-client-0.3.1 lib/wcc/blogs/client.rb
wcc-blogs-client-0.3.0 lib/wcc/blogs/client.rb
wcc-blogs-client-0.2.0 lib/wcc/blogs/client.rb
wcc-blogs-client-0.1.1 lib/wcc/blogs/client.rb
wcc-blogs-client-0.1.0 lib/wcc/blogs/client.rb