Sha256: 086835effc46454edcfe615db98d9f8b070041b80fc0f93087000e0c951b6e0a

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

require "net/http"
require "json"
require "active_support/time"
require_relative "utils"

module DevOrbit
  class Dev
    def initialize(params = {})
      @username = params.fetch(:username, ENV["DEV_USERNAME"])
      @api_key = params.fetch(:api_key, ENV["DEV_API_KEY"])
      @workspace_id = params.fetch(:workspace_id, ENV["ORBIT_WORKSPACE_ID"])
      @orbit_api_key = params.fetch(:orbit_api_key, ENV["ORBIT_API_KEY"])
    end

    def process_comments
      articles = get_articles

      articles.each do |article|
        comments = get_article_comments(article["id"])

        next if comments.nil? || comments.empty?

        DevOrbit::Orbit.call(
          type: "comments",
          data: {
            comments: comments,
            title: article["title"],
            url: article["url"]
          },
          workspace_id: @workspace_id,
          api_key: @orbit_api_key
        )
      end
    end

    private

    def get_articles
      url = URI("https://dev.to/api/articles?username=#{@username}&top=1")
      https = Net::HTTP.new(url.host, url.port)
      https.use_ssl = true

      request = Net::HTTP::Get.new(url)

      response = https.request(request)

      JSON.parse(response.body) if DevOrbit::Utils.valid_json?(response.body)
    end

    def get_article_comments(id)
      url = URI("https://dev.to/api/comments?a_id=#{id}")
      https = Net::HTTP.new(url.host, url.port)
      https.use_ssl = true

      request = Net::HTTP::Get.new(url)

      response = https.request(request)

      comments = JSON.parse(response.body) if DevOrbit::Utils.valid_json?(response.body)

      return if comments.nil? || comments.empty?

      filter_comments(comments)
    end

    def filter_comments(comments)
      comments.select do |comment|
        comment["created_at"] >= 1.day.ago
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dev_orbit-0.0.8 lib/dev_orbit/dev.rb