Sha256: 367f99499043d03711d056212d0ad66915ea35adc0cfd5a7684c656f00be94a1

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

require 'net/http'
require 'json'
require_relative "api_analytics/version"

module Analytics
  class Middleware
    def initialize(app)
      @app = app
      @api_key = Rails.application.secrets.ANALYTICS_API_KEY
      raise StandardError.new 'ANALYTICS_API_KEY secret unset.' if @api_key.nil?
    end

    def call(env)
      start = Time.now
      status, headers, response = @app.call(env)

      json = {
        api_key: @api_key,
        hostname: env['HTTP_HOST'],
        path: env['REQUEST_PATH'],
        user_agent: env['HTTP_USER_AGENT'],
        method: env['REQUEST_METHOD'],
        status: status,
        framework: "Rails",
        response_time: (Time.now - start).to_f.round,
      }

      Thread.new {
        log_request(json)
      }

      [status, headers, response]
    end

    private

    def log_request(json)
      uri = URI('https://api-analytics-server.vercel.app/api/log-request')
      http = Net::HTTP.new(uri.host, uri.port)
      Rails.logger.info("#{uri.host} #{uri.port} #{uri.path}")
      req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
      req.body = json.to_json
      res = http.request(req)
    rescue => e
    end
  end
end


Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
api_analytics-1.0.1 lib/api_analytics.rb