Skip to content

Commit

Permalink
chore: Refactor Caido::Instance class initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
hahwul committed Jun 23, 2024
1 parent a8347f5 commit e8e773a
Showing 1 changed file with 16 additions and 26 deletions.
42 changes: 16 additions & 26 deletions lib/caido/instance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,54 +4,44 @@
require 'json'

# Assuming this code is at the top level of instance.rb and helplers directory is at the same level
Dir[File.expand_path('helpers/*.rb', __dir__)].sort.each { |file| require file }
Dir[File.expand_path('helpers/*.rb', __dir__)].each { |file| require file }

module Caido
# Instance class
class Instance
attr_reader :graphql_url, :authorization

def initialize(*args)
set_defaults
process_arguments(args)
auth_from_env
end

private

def set_defaults
@graphql_url = 'http://localhost:8080/graphql'
@authorization = nil
end

def process_arguments(args)
case args.size
when 0
# Initialize with default values
when 1
# Initialize with graphql_url
@graphql_url = args[0]
when 2
# Initialize with graphql_url and authorization
@graphql_url, authorization = args
@authorization = if authorization.include?('Bearer ')
authorization
else
"Bearer #{authorization}"
end
else
@authorization = format_authorization(authorization)
when args.size > 2
raise ArgumentError, 'Too many arguments provided'
end
end

auth_from_env if @authorization.nil?
def format_authorization(auth)
auth.include?('Bearer ') ? auth : "Bearer #{auth}"
end

def auth_from_env
@auth_from_env ||= ENV.fetch('CAIDO_AUTH_TOKEN', 'Bearer ')
end

def query(query)
res = HTTParty.post(
graphql_url,
body: { query: query }.to_json,
headers: {
'Content-Type' => 'application/json',
'Authorization' => authorization
}
)

obj = JSON.parse(res.body)
obj['data']
end
end
end

0 comments on commit e8e773a

Please sign in to comment.