Sha256: d3559b5d6ebe11c0d700b4160b2d664dddcf1b6855eb02eb6169e75f1bfe4eee

Contents?: true

Size: 1.86 KB

Versions: 1

Compression:

Stored size: 1.86 KB

Contents

# frozen_string_literal: true
require 'http'

module FaceGroup
  # Service for all FB API calls
  class FbApi
    FB_URL = 'https://graph.facebook.com'
    API_VER = 'v2.8'
    FB_API_URL = [FB_URL, API_VER].join('/')
    FB_TOKEN_URL = [FB_API_URL, 'oauth/access_token'].join('/')
    TOKEN_KEY = 'fbapi_access_token'

    def self.access_token
      return @access_token if @access_token

      access_token_response =
        HTTP.get(FB_TOKEN_URL,
                 params: { client_id: config[:client_id],
                           client_secret: config[:client_secret],
                           grant_type: 'client_credentials' })
      @access_token = access_token_response.parse['access_token']
    end

    def self.config=(credentials)
      @config = {} unless @config
      @config.update(credentials)
    end

    def self.config
      return @config if @config
      @config = { client_id: ENV['FB_CLIENT_ID'],
                  client_secret: ENV['FB_CLIENT_SECRET'] }
    end

    def self.group_feed(group_id)
      feed_response = HTTP.get(
        fb_resource_url(group_id) + '/feed',
        params: { access_token: access_token }
      )
      JSON.load(feed_response.to_s)
    end

    def self.fb_resource(id)
      response = HTTP.get(
        fb_resource_url(id),
        params: { access_token: access_token }
      )
      JSON.load(response.to_s)
    end

    def self.group_info(group_id)
      fb_resource(group_id)
    end

    def self.posting(posting_id)
      fb_resource(posting_id)
    end

    def self.posting_attachments(posting_id)
      attachments_response = HTTP.get(
        fb_resource_url(posting_id) + '/attachments',
        params: { access_token: access_token }
      )
      JSON.load(attachments_response.to_s)['data'].first
    end

    private_class_method

    def self.fb_resource_url(id)
      URI.join(FB_API_URL, id.to_s).to_s
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facegroup-0.1.0 lib/facegroup/fb_api.rb