require 'restclient' require 'active_support/all' module RailsConnector # Provides a simple wrapper for the CMS Rest API # using the credentials from {RailsConnector::Configuration.cms_api_options}. # # @example Request the published workspace: # RailsConnector::CmsRestApi.get('workspaces/published') # # @example Create a new Obj: # RailsConnector::CmsRestApi.post('revisions/001384beff9e5845/objs', # {'obj' => {'_path' => '/new_obj', '_obj_class' => 'Publication'}}) # # @example Update an Obj: # RailsConnector::CmsRestApi.put('revisions/001384beff9e5845/objs/9e432077f0412a63', # {'obj' => {'title' => 'new title'}}) # # @example Delete an Obj: # RailsConnector::CmsRestApi.delete('revisions/001384beff9e5845/objs/f4123622ff07b70b') class CmsRestApi cattr_accessor :credentials def self.get(resource_path, payload = nil) request_cms_api(:get, resource_path, payload) end def self.put(resource_path, payload) request_cms_api(:put, resource_path, payload) end def self.post(resource_path, payload) request_cms_api(:post, resource_path, payload) end def self.delete(resource_path, payload = nil) request_cms_api(:delete, resource_path, payload) end # @param [Hash] value # @return [void] def self.credentials=(value) @@credentials = value.symbolize_keys end private def self.request_cms_api(action, resource_path, payload) request_params = basic_request_params request_params[:method] = action request_params[:url] = url(resource_path) request_params[:payload] = MultiJson.encode(payload) if payload.present? begin MultiJson.decode(RestClient::Request.execute(request_params)) rescue RestClient::ExceptionWithResponse => e begin if e.http_code == 403 raise AccessDenied.new(e.http_body) elsif e.http_code.to_s.match(/4\d{2}/) && (specific_output = MultiJson.decode(e.http_body)['error']) raise ClientError.new(specific_output, e.http_code) end rescue MultiJson::DecodeError end raise BackendNotAvailable.new(e.http_body, e.http_code) end end def self.basic_request_params headers = { :content_type => :json, :accept => :json, } headers[:host] = credentials[:http_host] if credentials[:http_host].present? { :user => credentials[:login], :password => credentials[:api_key], :headers => headers, } end def self.url(resource_path) "#{credentials[:url]}/#{resource_path}" end end end