module MidasClient class Request include Util include RestClient attr_accessor :login, :password def initialize(login, password) @login = login @password = password log("POS #{login} INITIALIZED!") end # Method that's wrap generic response def base_result(success, code, message) { result: { success: success, code: code, message: "#{message}" } }.to_hash end # Method that's wrap rest-client generic request def request(method, endpoint, login, password, parameters={}, headers={content_type: :json, accept: :json}) # inicia a contagem da execução start_time_execution = Time.now log "METHOD: #{method} URL: #{endpoint} login: #{login} password: #{password} payload: #{self.sanitize_pci(parameters)}" begin response = RestClient::Request.execute(method: method, url: endpoint, user: login, password: password, content_type: :json, ssl_version: :TLSv1_2, payload: (parameters.to_json unless parameters.nil?), headers: headers) rescue => e response = e.response || e end # parsing da resposta begin response = JSON.parse(response, symbolize_names: true ) rescue => e error_log "METHOD: #{method} URL: #{endpoint} login: #{login} Mensagem: #{e.to_s}" response = base_result(false, '999', "Operação não concluída. Motivo: #{e.to_s}") ensure total_time_execution = Time.now - start_time_execution log "[RESPONSE] #{self.sanitize_pci(response)}" log "Executado #{method} URL: #{endpoint} LOGIN: #{login} TEMPO: #{total_time_execution}s SUCCESS: #{response[:result][:success]}" end response end # Method to call any other def self.external_request(method, endpoint, parameters={}, headers={content_type: :json, accept: :json}) # inicia a contagem da execução start_time_execution = Time.now log "[EXTERNAL][REQUEST][#{method}] URL: #{endpoint} payload: #{sanitize_pci(parameters)}" begin response = RestClient::Request.execute(method: method, url: endpoint, payload: (parameters.to_json unless parameters.nil?), headers: headers) rescue => e response = e.response || e end # parsing da resposta begin response = JSON.parse(response, symbolize_names: true ) rescue => e error_log "[EXTERNAL][REQUEST]METHOD: #{method} URL: #{endpoint} Mensagem: #{e.to_s}" response = base_result(false, '999', "Operação não concluída. Motivo: #{e.to_s}") ensure total_time_execution = Time.now - start_time_execution log "[EXTERNAL][RESPONSE][#{method}] URL: #{endpoint} TEMPO: #{total_time_execution}s RESULT: #{self.sanitize_pci(response)}" end response end end end