Created
April 18, 2021 10:53
-
-
Save Chocksy/4b098fdd81041e217c5b48e8e41ddb29 to your computer and use it in GitHub Desktop.
Simple adapter class that talks with Cloudflare API to allow for cache purge. It uses faraday for requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Cloudflare adapter to help us communicate with the cloudflare API. | |
# Usage: | |
# cloudflare = Cloudflare.new(zone: '123', api_key: '2323', email: '[email protected]') | |
# cloudflare.purge_everything | |
# cloudflare.zones | |
class Cloudflare | |
CLOUDFLARE_API_ENDPOINT = 'https://api.cloudflare.com/client/v4' | |
attr_reader :zone, :api_key, :email | |
def initialize(zone:, api_key:, email:) | |
@zone = zone | |
@api_key = api_key | |
@email = email | |
end | |
# Purge everything from the set zone. It makes a simple post request to the API with purge_everything as param. | |
def purge_everything | |
Rails.logger.info 'Purging cache on Cloudflare'.yellow | |
data = {purge_everything: true} | |
response = connection.post("zones/#{zone}/purge_cache", data) | |
raise StandardError, "Unable to purge Cloudflare cache: #{response.body['errors']}" unless response.body['success'] | |
Rails.logger.info 'Purged cache on Cloudflare'.green | |
end | |
# Returns all the zones for this account. | |
# @return [Hash] | |
def zones | |
connection.get('zones').body | |
end | |
private | |
# Faraday connection that defines the headers and response content types | |
def connection | |
Faraday.new(url: CLOUDFLARE_API_ENDPOINT) do |conn| | |
conn.headers['Content-Type'] = 'application/json' | |
conn.headers['X-Auth-Key'] = api_key | |
conn.headers['X-Auth-Email'] = email | |
conn.request :json | |
conn.response :json, content_type: /\bjson$/ | |
conn.adapter Faraday.default_adapter | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment